<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Python深入和提高 | SanShui的个人博客</title><meta name="author" content="SanShui"><meta name="copyright" content="SanShui"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="Python深入和提高">
<meta property="og:type" content="article">
<meta property="og:title" content="Python深入和提高">
<meta property="og:url" content="https://huaiyuechusan.github.io/archives/8df5f8b9.html">
<meta property="og:site_name" content="SanShui的个人博客">
<meta property="og:description" content="Python深入和提高">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://wallpaper.csun.site/?5">
<meta property="article:published_time" content="2023-12-12T13:44:00.000Z">
<meta property="article:modified_time" content="2024-10-17T11:57:36.906Z">
<meta property="article:author" content="SanShui">
<meta property="article:tag" content="学习技术">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://wallpaper.csun.site/?5"><link rel="shortcut icon" href="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg"><link rel="canonical" href="https://huaiyuechusan.github.io/archives/8df5f8b9"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Python深入和提高',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-10-17 19:57:36'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/echarts@4.9.0/dist/echarts.min.js"></script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="/./css/runtime.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="SanShui的个人博客" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (true) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg" onerror="onerror=null;src='./img/config_img/蓝天.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://wallpaper.csun.site/?5')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">SanShui的个人博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Python深入和提高</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-12-12T13:44:00.000Z" title="发表于 2023-12-12 21:44:00">2023-12-12</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-10-17T11:57:36.906Z" title="更新于 2024-10-17 19:57:36">2024-10-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Python/">Python</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">23.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>94分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Python深入和提高"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><meta name="referrer" content="no-referrer" />

<h1 id="Python深入和提高"><a href="#Python深入和提高" class="headerlink" title="Python深入和提高"></a>Python深入和提高</h1><h2 id="异常机制"><a href="#异常机制" class="headerlink" title="异常机制"></a>异常机制</h2><h3 id="异常的本质-调试错误的核心理念"><a href="#异常的本质-调试错误的核心理念" class="headerlink" title="异常的本质-调试错误的核心理念"></a>异常的本质-调试错误的核心理念</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555906.png" alt="image-20231119182040284"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555908.png" alt="image-20231121150902973"></p>
<h3 id="try-except基本结构"><a href="#try-except基本结构" class="headerlink" title="try_except基本结构"></a>try_except基本结构</h3><p><strong>try…一个except结构</strong></p>
<p>try…except是最常见的异常处理结构。结构如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    被监控可能发生引起异常的语句块</span><br><span class="line"><span class="keyword">except</span> BaseException [<span class="keyword">as</span> e]:</span><br><span class="line">    异常处理语句</span><br></pre></td></tr></table></figure>
<ol>
<li><code>try</code>块包含着可能引发异常的代码，<code>except</code>块则用来捕捉和处理发生的异常。</li>
<li>执行的时候，如果<code>try</code>块中没有引发异常，则跳过<code>except</code>块继续执行后续代码；</li>
<li>执行的时候，如果<code>try</code>块中发生了异常，则跳过<code>try</code>块中的后续代码，跳到相应的<code>except</code></li>
<li>块中处理异常；异常处理完后，继续执行后续代码。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;step1&quot;</span>)</span><br><span class="line">    a = <span class="number">2</span> / <span class="number">0</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;step2&quot;</span>)</span><br><span class="line"><span class="keyword">except</span> BaseException <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;step3&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;step4&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">step1</span></span><br><span class="line"><span class="string">step3</span></span><br><span class="line"><span class="string">division by zero</span></span><br><span class="line"><span class="string">step4</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="try-多个except结构"><a href="#try-多个except结构" class="headerlink" title="try_多个except结构"></a>try_多个except结构</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    a = <span class="built_in">input</span>(<span class="string">&quot;请输入被除数：&quot;</span>)</span><br><span class="line">    b = <span class="built_in">input</span>(<span class="string">&quot;请输入除数：&quot;</span>)</span><br><span class="line">    c = <span class="built_in">float</span>(a)/<span class="built_in">float</span>(b)</span><br><span class="line">    <span class="built_in">print</span>(c)</span><br><span class="line"><span class="keyword">except</span> ZeroDivisionError:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;异常，除数不能为0&quot;</span>)</span><br><span class="line"><span class="keyword">except</span> TypeError:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;异常：除数和被除数都应该为数值类型&quot;</span>)</span><br><span class="line"><span class="keyword">except</span> BaseException <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e))</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">请输入被除数：1</span></span><br><span class="line"><span class="string">请输入除数：dd</span></span><br><span class="line"><span class="string">could not convert string to float: &#x27;dd&#x27;</span></span><br><span class="line"><span class="string">&lt;class &#x27;ValueError&#x27;&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="try…except…else结构"><a href="#try…except…else结构" class="headerlink" title="try…except…else结构"></a>try…except…else结构</h3><p><code>try..except...else</code>结构增加了<code>else</code>块。如果<code>try</code>块中没有抛出异常，则执行<code>else</code>块。如果<code>try</code>块中抛出异常，则执行<code>except</code>块，不执行<code>else</code>块。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    a = <span class="built_in">input</span>(<span class="string">&quot;请输入被除数：&quot;</span>)</span><br><span class="line">    b = <span class="built_in">input</span>(<span class="string">&quot;请输入除数：&quot;</span>)</span><br><span class="line">    c = <span class="built_in">float</span>(a)/<span class="built_in">float</span>(b)</span><br><span class="line">    <span class="built_in">print</span>(c)</span><br><span class="line"><span class="keyword">except</span> BaseException <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e))</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;除的结果为：&quot;</span>, c)</span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">请输入被除数：3</span></span><br><span class="line"><span class="string">请输入除数：4</span></span><br><span class="line"><span class="string">0.75</span></span><br><span class="line"><span class="string">除的结果为： 0.75</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="try…except…finally结构和return语句位置"><a href="#try…except…finally结构和return语句位置" class="headerlink" title="try…except…finally结构和return语句位置"></a>try…except…finally结构和return语句位置</h3><p><code>try...except..finally</code>结构中，<code>finally</code>块无论是否发生异常都会被执行；通常用来释放<code>try</code>块中申请的资源。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    a = <span class="built_in">input</span>(<span class="string">&quot;请输入被除数：&quot;</span>)</span><br><span class="line">    b = <span class="built_in">input</span>(<span class="string">&quot;请输入除数：&quot;</span>)</span><br><span class="line">    c = <span class="built_in">float</span>(a)/<span class="built_in">float</span>(b)</span><br><span class="line">    <span class="built_in">print</span>(c)</span><br><span class="line"><span class="keyword">except</span> BaseException <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e))</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;除的结果为：&quot;</span>, c)</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;我是finally语句，无论是否发生异常我都会被执行&quot;</span>)</span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">请输入被除数：3</span></span><br><span class="line"><span class="string">请输入除数：0</span></span><br><span class="line"><span class="string">float division by zero</span></span><br><span class="line"><span class="string">&lt;class &#x27;ZeroDivisionError&#x27;&gt;</span></span><br><span class="line"><span class="string">我是finally语句，无论是否发生异常我都会被执行</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><strong>return语句和异常处理问题</strong></p>
<p>由于<code>return</code>有两种作用：结束方法运行、返回值。我们一般不把<code>return</code>放到异常处理结构中，而是放到方法最后。</p>
<h3 id="常见异常汇总说明"><a href="#常见异常汇总说明" class="headerlink" title="常见异常汇总说明"></a>常见异常汇总说明</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555909.png" alt="image-20231120213240849"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555910.png" alt="image-20231120213330316"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555911.png" alt="image-20231120213358038"></p>
<div class="table-container">
<table>
<thead>
<tr>
<th><strong>异常名称</strong></th>
<th style="text-align:center"><strong>说明</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>ArithmeticError</td>
<td style="text-align:center">所有数值计算错误的基类</td>
</tr>
<tr>
<td>AssertionError</td>
<td style="text-align:center">断言语句失败</td>
</tr>
<tr>
<td>AttributeError</td>
<td style="text-align:center">对象没有这个属性</td>
</tr>
<tr>
<td>BaseException</td>
<td style="text-align:center">所有异常的基类</td>
</tr>
<tr>
<td>DeprecationWarning</td>
<td style="text-align:center">关于被弃用的特征的警告</td>
</tr>
<tr>
<td>EnvironmentError</td>
<td style="text-align:center">操作系统错误的基类</td>
</tr>
<tr>
<td>EOFError</td>
<td style="text-align:center">没有内建输入,到达EOF 标记</td>
</tr>
<tr>
<td>Exception</td>
<td style="text-align:center">常规错误的基类</td>
</tr>
<tr>
<td>FloatingPointError</td>
<td style="text-align:center">浮点计算错误</td>
</tr>
<tr>
<td>FutureWarning</td>
<td style="text-align:center">关于构造将来语义会有改变的警告</td>
</tr>
<tr>
<td>GeneratorExit</td>
<td style="text-align:center">生成器(generator)发生异常来通知退出</td>
</tr>
<tr>
<td>ImportError</td>
<td style="text-align:center">导入模块/对象失败</td>
</tr>
<tr>
<td>IndentationError</td>
<td style="text-align:center">缩进错误</td>
</tr>
<tr>
<td>IndexError</td>
<td style="text-align:center">序列中没有此索引(index)</td>
</tr>
<tr>
<td>IOError</td>
<td style="text-align:center">输入/输出操作失败</td>
</tr>
<tr>
<td>KeyboardInterrupt</td>
<td style="text-align:center">用户中断执行(通常是输入^C)</td>
</tr>
<tr>
<td>KeyError</td>
<td style="text-align:center">映射中没有这个键</td>
</tr>
<tr>
<td>LookupError</td>
<td style="text-align:center">无效数据查询的基类</td>
</tr>
<tr>
<td>MemoryError</td>
<td style="text-align:center">内存溢出错误(对于Python 解释器不是致命的)</td>
</tr>
<tr>
<td>NameError</td>
<td style="text-align:center">未声明/初始化对象 (没有属性)</td>
</tr>
<tr>
<td>NotImplementedError</td>
<td style="text-align:center">尚未实现的方法</td>
</tr>
<tr>
<td>OSError</td>
<td style="text-align:center">操作系统错误</td>
</tr>
<tr>
<td>OverflowError</td>
<td style="text-align:center">数值运算超出最大限制</td>
</tr>
<tr>
<td>OverflowWarning</td>
<td style="text-align:center">旧的关于自动提升为长整型(long)的警告</td>
</tr>
<tr>
<td>PendingDeprecationWarning</td>
<td style="text-align:center">关于特性将会被废弃的警告</td>
</tr>
<tr>
<td>ReferenceError</td>
<td style="text-align:center">弱引用(Weak reference)试图访问已经垃圾回收了的对象</td>
</tr>
<tr>
<td>RuntimeError</td>
<td style="text-align:center">一般的运行时错误</td>
</tr>
<tr>
<td>RuntimeWarning</td>
<td style="text-align:center">可疑的运行时行为(runtime behavior)的警告</td>
</tr>
<tr>
<td>StandardError</td>
<td style="text-align:center">所有的内建标准异常的基类</td>
</tr>
<tr>
<td>StopIteration</td>
<td style="text-align:center">迭代器没有更多的值</td>
</tr>
<tr>
<td>SyntaxError</td>
<td style="text-align:center">Python 语法错误</td>
</tr>
<tr>
<td>SyntaxWarning</td>
<td style="text-align:center">可疑的语法的警告</td>
</tr>
<tr>
<td>SystemError</td>
<td style="text-align:center">一般的解释器系统错误</td>
</tr>
<tr>
<td>SystemExit</td>
<td style="text-align:center">解释器请求退出</td>
</tr>
<tr>
<td>TabError</td>
<td style="text-align:center">Tab 和空格混用</td>
</tr>
<tr>
<td>TypeError</td>
<td style="text-align:center">对类型无效的操作</td>
</tr>
<tr>
<td>UnboundLocalError</td>
<td style="text-align:center">访问未初始化的本地变量</td>
</tr>
<tr>
<td>UnicodeDecodeError</td>
<td style="text-align:center">Unicode 解码时的错误</td>
</tr>
<tr>
<td>UnicodeEncodeError</td>
<td style="text-align:center">Unicode 编码时错误</td>
</tr>
<tr>
<td>UnicodeError</td>
<td style="text-align:center">Unicode 相关的错误</td>
</tr>
<tr>
<td>UnicodeTranslateError</td>
<td style="text-align:center">Unicode 转换时错误</td>
</tr>
<tr>
<td>UserWarning</td>
<td style="text-align:center">用户代码生成的警告</td>
</tr>
<tr>
<td>ValueError</td>
<td style="text-align:center">传入无效的参数</td>
</tr>
<tr>
<td>Warning</td>
<td style="text-align:center">警告的基类</td>
</tr>
<tr>
<td>WindowsError</td>
<td style="text-align:center">系统调用失败</td>
</tr>
<tr>
<td>ZeroDivisionError</td>
<td style="text-align:center">除(或取模)零 (所有数据类型)</td>
</tr>
</tbody>
</table>
</div>
<h3 id="with上下文管理资源"><a href="#with上下文管理资源" class="headerlink" title="with上下文管理资源"></a>with上下文管理资源</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555912.png" alt="image-20231121151122084"></p>
<p>​    </p>
<p><code>finally</code>块由于是否发生异常都会执行，通常我们放释放资源的代码。其实，我们可以通过<code>with</code>上下文管理，更方便的实现释放资源的操作。</p>
<p><code>with</code>上下文管理的语法结构如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> context_expr [ <span class="keyword">as</span> var]:</span><br><span class="line">    语句块</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>with</code>上下文管理可以自动管理资源，在<code>with</code>代码块执行完毕后自动还原进入该代码之前的现场或上下文。不论何种原因跳出<code>with</code>块，不论是否有异常，==总能保证资源正常释放==。极大的简化了工作，在文件操作、网络通信相关的场合非常常用。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&quot;d:/test.txt&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    context = f.readline()</span><br><span class="line">    <span class="built_in">print</span>(context)</span><br></pre></td></tr></table></figure>
<h3 id="traceback模块的使用-异常写入日志文件"><a href="#traceback模块的使用-异常写入日志文件" class="headerlink" title="traceback模块的使用-异常写入日志文件"></a>traceback模块的使用-异常写入日志文件</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555913.png" alt="image-20231121152312711"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> traceback</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;step1&quot;</span>)</span><br><span class="line">    num = <span class="number">1</span> / <span class="number">0</span></span><br><span class="line"><span class="keyword">except</span>:</span><br><span class="line">    traceback.print_exc()  <span class="comment"># 打印异常信息</span></span><br></pre></td></tr></table></figure>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> traceback</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;step1&quot;</span>)</span><br><span class="line">    num = <span class="number">1</span> / <span class="number">0</span></span><br><span class="line"><span class="keyword">except</span>:</span><br><span class="line">    <span class="comment"># 将异常信息输出到文件</span></span><br><span class="line">    <span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&quot;d:/test.txt&quot;</span>, <span class="string">&quot;a&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">        traceback.print_exc(file=f)</span><br></pre></td></tr></table></figure>
<h3 id="自定义异常-raise抛出异常"><a href="#自定义异常-raise抛出异常" class="headerlink" title="自定义异常-raise抛出异常"></a>自定义异常-raise抛出异常</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555914.png" alt="image-20231121153406627"></p>
<p>程序开发中，有时候我们也需要自己定义异常类。自定义异常类一般都是运行时异常，通常继承<code>Exception</code>或其子类即可。命名一般以<code>Error</code>、<code>Exception</code>为后缀。</p>
<p><strong>自定义异常由<code>raise</code>语句主动抛出。</strong></p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 自定义异常类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AgeError</span>(<span class="title class_ inherited__">Exception</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, errorinfo</span>):</span><br><span class="line">        Exception.__init__(self)</span><br><span class="line">        self.errorinfo = errorinfo</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">str</span>(self.errorinfo) + <span class="string">&quot;,年龄错误，应该在1-150之间&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:  <span class="comment"># 如果是true，则模块是作独立文件执行，下面可以写测试代码</span></span><br><span class="line">    age = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&quot;输入一个年龄：&quot;</span>))</span><br><span class="line">    <span class="keyword">if</span> age &lt; <span class="number">1</span> <span class="keyword">or</span> age &gt; <span class="number">150</span>:</span><br><span class="line">        <span class="keyword">raise</span> AgeError(age)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;正常的年龄：&quot;</span>, age)</span><br><span class="line">        </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">输入一个年龄：170</span></span><br><span class="line"><span class="string">Traceback (most recent call last):</span></span><br><span class="line"><span class="string">  File &quot;D:\2022百战Python\Python深入和提高\异常机制\practice.py&quot;, line 86, in &lt;module&gt;</span></span><br><span class="line"><span class="string">    raise AgeError(age)</span></span><br><span class="line"><span class="string">__main__.AgeError: 170,年龄错误，应该在1-150之间</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="Pycharm调试模式debug视图"><a href="#Pycharm调试模式debug视图" class="headerlink" title="Pycharm调试模式debug视图"></a>Pycharm调试模式debug视图</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555915.png" alt="image-20231121155153724"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555917.png" alt="image-20231121155224700"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555918.png" alt="image-20231121155244514"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311211555919.png" alt="image-20231121155300946"></p>
<h2 id="文件处理"><a href="#文件处理" class="headerlink" title="文件处理"></a>文件处理</h2><h3 id="fle文件操作-操作系统底层关系-写入文件"><a href="#fle文件操作-操作系统底层关系-写入文件" class="headerlink" title="fle文件操作-操作系统底层关系-写入文件"></a>fle文件操作-操作系统底层关系-写入文件</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220078.png" alt="image-20231121161102367"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220080.png" alt="image-20231121161205752"></p>
<p>Python标准库中，如下是文件操作相关的模块:</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>io模块</td>
<td>文件流的输入和输出操作 input output</td>
</tr>
<tr>
<td>os模块</td>
<td>基本操作系统功能，包括文件操作</td>
</tr>
<tr>
<td>glob模块</td>
<td>查找符合特定规则的文件路径名</td>
</tr>
<tr>
<td>fnmatch模块</td>
<td>使用模式来匹配文件路径名</td>
</tr>
<tr>
<td>fileinput模块</td>
<td>处理多个输入文件</td>
</tr>
<tr>
<td>filecmp模块</td>
<td>用于文件的比较</td>
</tr>
<tr>
<td>csv模块</td>
<td>用于csv文件处理</td>
</tr>
<tr>
<td>pickle和cPickle</td>
<td>用于序列化和反序列化</td>
</tr>
<tr>
<td>xml包</td>
<td>用于XML数据处理</td>
</tr>
<tr>
<td>bz2、gzip、zipfile、zlib、tarfile</td>
<td>用于处理压缩和解压缩文件（分别对应不同的算法）</td>
</tr>
</tbody>
</table>
</div>
<p><strong>创建文件对象open()</strong></p>
<p>open0函数用于创建文件对象，基本语法格式如下：</p>
<p><code>open(文件名[打开方式])</code></p>
<p>如果只是文件名，代表在当前目录下的文件。文件名可以录入全路径，比如：<code>D:\a\b.txt</code></p>
<p>为了减少<code>\</code>的输入，可以使用原始字符串：<code>r &quot;d:\b.txt”</code>示例如下：</p>
<p><code>f = open(r&quot;d:\b.txt&quot;, &quot;w&quot;)</code></p>
<p>打开方式有如下几种：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>模式</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>r</td>
<td>读read模式</td>
</tr>
<tr>
<td>w</td>
<td>写wite模式。如果文件不存在则创建；如果文件存在，则重写新内容</td>
</tr>
<tr>
<td>a</td>
<td>追加append模式。如果文件不存在则创建；如果文件存在，则在文件<strong>末尾追加内容</strong></td>
</tr>
<tr>
<td>b</td>
<td>二进制binary模式（可与其他模式组合使用）</td>
</tr>
<tr>
<td>+</td>
<td>读、写模式（可与其他模式组合使用）</td>
</tr>
</tbody>
</table>
</div>
<blockquote>
<p>文本文件对象和二进制文件对象的创建：</p>
<ol>
<li>如果没有增加模式<code>b</code>,则<strong>默认创建的是文本文件对象</strong>，处理的基本单元是“字符”。</li>
<li>如果是二进制模式<code>b</code>,则创建的是二进制文件对象，处理的基本单元是“字节”。</li>
</ol>
</blockquote>
<p><strong>基本的文件写入操作</strong></p>
<p>文本文件的写入一般就是三个步骤：</p>
<ol>
<li>创建文件对象</li>
<li>写入数据</li>
<li>关闭文件对象</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">f = <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;a&quot;</span>)</span><br><span class="line">f.write(<span class="string">&quot;hello world&quot;</span>)</span><br><span class="line">f.close()</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;a&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(<span class="string">&quot;hello world&quot;</span>)</span><br></pre></td></tr></table></figure>
<h3 id="编码知识-中文乱码问题解决"><a href="#编码知识-中文乱码问题解决" class="headerlink" title="编码知识-中文乱码问题解决"></a>编码知识-中文乱码问题解决</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220081.png" alt="image-20231121194831439"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220082.png" alt="image-20231121195124583"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 指定文件编码解决中文乱码问题</span></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;a&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(<span class="string">&quot;你好&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><strong>write()/writelines()写入数据</strong></p>
<p><code>write(a)</code>:把字符串a写入到文件中</p>
<p><code>writelines(b)</code>：把字符串列表事入文件中，不添加换行符</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;w&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    <span class="comment"># f.write(&quot;你好&quot;)</span></span><br><span class="line">    s = [<span class="string">&quot;年龄\n&quot;</span>, <span class="string">&quot;姓名\n&quot;</span>, <span class="string">&quot;学校\n&quot;</span>]</span><br><span class="line">    f.writelines(s)</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220083.png" alt="image-20231121195750398"></p>
<h3 id="关闭流要点"><a href="#关闭流要点" class="headerlink" title="关闭流要点"></a>关闭流要点</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220084.png" alt="image-20231121195847695"></p>
<p>由于文件底层是由操作系统控制，所以我们打开的文件对象必须<strong>显式调用</strong><code>close()</code>方法关闭文件对象。当调用<code>close()</code>方法时，首先会把缓冲区数据写入文件（也可以直接调用<code>flush()</code>方法），再关闭文件，释放文件对象。</p>
<p>为了确保打开的文件对象正常关闭，一般结合异常机制的<code>finally</code>或者<code>with</code>关键字实现无论何种情况都能关闭打开的文件对象。</p>
<h4 id="finally异常管理"><a href="#finally异常管理" class="headerlink" title="finally异常管理"></a>finally异常管理</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 结合异常机制的finally,确保关闭文件对象</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    f = <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;w&quot;</span>)</span><br><span class="line">    s = <span class="string">&quot;hello world&quot;</span></span><br><span class="line">    f.write(s)</span><br><span class="line"><span class="keyword">except</span> BaseException <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    f.close()</span><br></pre></td></tr></table></figure>
<h4 id="with上下文管理"><a href="#with上下文管理" class="headerlink" title="with上下文管理"></a>with上下文管理</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用with管理文件写入操作</span></span><br><span class="line">s = [<span class="string">&quot;年龄\n&quot;</span>, <span class="string">&quot;姓名\n&quot;</span>, <span class="string">&quot;学校\n&quot;</span>]</span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;w&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.writelines(s)</span><br></pre></td></tr></table></figure>
<h3 id="文本文件的读取"><a href="#文本文件的读取" class="headerlink" title="文本文件的读取"></a>文本文件的读取</h3><p>文件的读取一般使用如下三个方法：</p>
<ol>
<li><p><code>read([size])</code></p>
<p>从文件中读取<code>size</code>个字符，并作为结果返回。<strong>如果没有<code>size</code>参数，则读取整个文件。</strong></p>
<p>读取到文件末尾，会返回空字符串。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    s = f.read(<span class="number">6</span>)</span><br><span class="line">    <span class="built_in">print</span>(s)</span><br><span class="line">    s2 = f.read()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;第二次读的：&quot;</span>, s2)</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">年龄</span></span><br><span class="line"><span class="string">姓名</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">第二次读的： 学校</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li><p><code>readline()</code></p>
<p>读取一行内容作为结果返回。读取到文件末尾，会返回空字符串</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    s = f.readline()</span><br><span class="line">    <span class="built_in">print</span>(s)</span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">年龄</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li><p><code>readlines()</code></p>
<p>文本文件中，每一行作为一个字符串存入列表中，返回该列表</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    s = f.readlines()</span><br><span class="line">    <span class="built_in">print</span>(s)</span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">[&#x27;年龄\n&#x27;, &#x27;姓名\n&#x27;, &#x27;学校\n&#x27;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> f:</span><br><span class="line">        <span class="built_in">print</span>(line, end=<span class="string">&quot;&quot;</span>)</span><br><span class="line"></span><br><span class="line">        </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">年龄</span></span><br><span class="line"><span class="string">姓名</span></span><br><span class="line"><span class="string">学校</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        line = f.readline()</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> line:</span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="built_in">print</span>(line, end=<span class="string">&quot;&quot;</span>)</span><br><span class="line">                     </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">年龄</span></span><br><span class="line"><span class="string">姓名</span></span><br><span class="line"><span class="string">学校</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="文本文件操作-为每行的末尾添加行号"><a href="#文本文件操作-为每行的末尾添加行号" class="headerlink" title="文本文件操作-为每行的末尾添加行号"></a>文本文件操作-为每行的末尾添加行号</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 为文本文件每行的末尾添加行号</span></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    lines = f.readlines()</span><br><span class="line">    <span class="built_in">print</span>(lines)</span><br><span class="line">    lines2 = [lines.rstrip() + <span class="string">&quot;#&quot;</span> + <span class="built_in">str</span>(index) + <span class="string">&quot;\n&quot;</span> <span class="keyword">for</span> index, lines <span class="keyword">in</span> <span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(lines) + <span class="number">1</span>), lines)]</span><br><span class="line">    <span class="built_in">print</span>(lines2)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;d:\test.txt&quot;</span>, <span class="string">&quot;w&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.writelines(lines2)</span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">[&#x27;年龄\n&#x27;, &#x27;姓名\n&#x27;, &#x27;学校\n&#x27;]</span></span><br><span class="line"><span class="string">[&#x27;年龄#1\n&#x27;, &#x27;姓名#2\n&#x27;, &#x27;学校#3\n&#x27;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="二进制文件的读写-图片文件的拷贝"><a href="#二进制文件的读写-图片文件的拷贝" class="headerlink" title="二进制文件的读写-图片文件的拷贝"></a>二进制文件的读写-图片文件的拷贝</h3><p>二进制文件的处理流程和文本文件流程一致。首先还是要创建文件对象，不过，我们需要指定二进制模式，从而创建出二进制文件对象。例如：</p>
<p><code>f=open(r&quot;d:\a.txt&quot;,wb)</code>        #可写的、重写模式的二进制文件对象</p>
<p><code>f=open(r&quot;d\a.txt&quot;,&#39;ab&#39;)</code>      #可写的、追加模式的二进制文件对象</p>
<p><code>f=open(r&quot;d:\a.txt&quot;,&#39;rb&#39;)</code>     #可读的二进制文件对象</p>
<p>创建好二进制文件对象后，仍然可以使用<code>wite()</code>、<code>read()</code>实现文件的读写操作。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">r&quot;src.png&quot;</span>, <span class="string">&quot;rb&quot;</span>) <span class="keyword">as</span> srcFile, <span class="built_in">open</span>(<span class="string">r&quot;dist.png&quot;</span>, <span class="string">&quot;wb&quot;</span>) <span class="keyword">as</span> distFile:</span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> srcFile:</span><br><span class="line">        distFile.write(line)</span><br></pre></td></tr></table></figure>
<h3 id="文件对象常用方法和属性总结-seek-任意位置操作"><a href="#文件对象常用方法和属性总结-seek-任意位置操作" class="headerlink" title="文件对象常用方法和属性总结-seek()任意位置操作"></a>文件对象常用方法和属性总结-seek()任意位置操作</h3><p><strong>文件对象的属性</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th>属性</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td>返回文件名字</td>
</tr>
<tr>
<td>mode</td>
<td>返回文件的打开模式</td>
</tr>
<tr>
<td>closed</td>
<td>若文件被关闭，则返回True</td>
</tr>
</tbody>
</table>
</div>
<p><strong>文件对象的打开方式</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th>属性</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>r</td>
<td>读模式</td>
</tr>
<tr>
<td>w</td>
<td>写模式</td>
</tr>
<tr>
<td>a</td>
<td>追加模式</td>
</tr>
<tr>
<td>b</td>
<td>二进制模式（可与其他模式组合）</td>
</tr>
<tr>
<td>+</td>
<td>读写模式（可与其他模式组合）</td>
</tr>
</tbody>
</table>
</div>
<p><strong>文件对象的常用方法</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th>方法名</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>read([size])</td>
<td>从文件中读取size个字节或字符的内容返回。若省略[size],则读取到文件末尾，即一次读取文件所有内容</td>
</tr>
<tr>
<td>readline()</td>
<td>从文本文件中读取一行内容</td>
</tr>
<tr>
<td>readlines()</td>
<td>把文本文件中每一行都作为独立的字符串对象，并将这些对象放入列表返回</td>
</tr>
<tr>
<td>write(str)</td>
<td>将字符串str内容写入文件</td>
</tr>
<tr>
<td>writelines(s)</td>
<td>将字符串列表s写入文件文件，不添加换行符</td>
</tr>
<tr>
<td>seek(offset [,whence])</td>
<td>把文件指针移动到新的位置，offset表示相对于whencet的多少个字节的偏移量。offset: off为正往结束方向移动，为负往开始方向移动                                            whence不同的值代表不同含义：0:从文件头开始计算（默认值）1：从当前位置开始计算2：从文件尾开始计算</td>
</tr>
<tr>
<td>tell()</td>
<td>返回文件指针的当前位置</td>
</tr>
<tr>
<td>truncate([size])</td>
<td>不论指针在什么位置，只留下指针前sz个字节的内容，其余全部删除；如果没有传入size,则当指针当前位置到文件末尾内容全部删除</td>
</tr>
<tr>
<td>flush()</td>
<td>把缓冲区的内容写入文件，但不关闭文件</td>
</tr>
<tr>
<td>close()</td>
<td>把缓冲区内容写入文件，同时关闭文件，释放文件对象相关资源</td>
</tr>
</tbody>
</table>
</div>
<h3 id="使用pickle实现序列化和反序列化"><a href="#使用pickle实现序列化和反序列化" class="headerlink" title="使用pickle实现序列化和反序列化"></a>使用pickle实现序列化和反序列化</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220085.png" alt="image-20231121220236689"></p>
<p>序列化指的是：将对象转化成“串行化”数据形式，存储到硬盘或通过网络传输到其他地方。</p>
<p>反序列化是指相反的过程，将读取到的“串行化数据”转化成对象。</p>
<p>我们可以使用pickle模块中的函数，实现序列化和反序列操作。</p>
<blockquote>
<p>Python中，一切皆对象，对象本质上就是一个“存储数据的内存块”。有时候，我们需要将“内存块的数据”保存到硬盘上，或者通过网络传输到其他的计算机上。这时候，就需要“对象的序列化和反序列化”。对象的序列化机制广泛的应用在分布式、并行系统上。</p>
</blockquote>
<p>序列化我们使用：</p>
<p><code>pickle.dump(obj, file)</code>   <code>obj</code>就是要被序列化的对象，<code>file</code>指的是存储的文件</p>
<p><code>pickle.load(file)</code>  从<code>file</code>读取数据，反序列化成对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pickle</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&quot;data.dat&quot;</span>, <span class="string">&quot;wb&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    name = <span class="string">&#x27;jack&#x27;</span></span><br><span class="line">    age = <span class="number">20</span></span><br><span class="line">    sorce = [<span class="number">70</span>, <span class="number">80</span>, <span class="number">90</span>]</span><br><span class="line">    resume = &#123;<span class="string">&#x27;name&#x27;</span>: name, <span class="string">&#x27;age&#x27;</span>: age, <span class="string">&#x27;sorce&#x27;</span>: sorce&#125;</span><br><span class="line">    pickle.dump(resume, f)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&quot;data.dat&quot;</span>, <span class="string">&quot;rb&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    resume2 = pickle.load(f)</span><br><span class="line">    <span class="built_in">print</span>(resume2)</span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&#123;&#x27;name&#x27;: &#x27;jack&#x27;, &#x27;age&#x27;: 20, &#x27;sorce&#x27;: [70, 80, 90]&#125;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="csv文件的读取和写入"><a href="#csv文件的读取和写入" class="headerlink" title="csv文件的读取和写入"></a>csv文件的读取和写入</h3><p>csv是逗号分隔符文本格式，常用于数据交换、Ec文件和数据库数据的导入和导出。</p>
<blockquote>
<p>与excel文件不同，csv文件中：</p>
<ul>
<li>值没有类型，所有值都是字符串</li>
<li>不能指定字体颜色等样式</li>
<li>不能指定单元格的宽高，不能合并单元格</li>
<li>没有多个工作表</li>
<li>不能嵌入图像图表</li>
</ul>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> csv</span><br><span class="line">        </span><br><span class="line"><span class="comment"># 写csv文件</span></span><br><span class="line">headers = [<span class="string">&quot;年龄&quot;</span>, <span class="string">&quot;姓名&quot;</span>]</span><br><span class="line">rows = [(<span class="number">20</span>, <span class="string">&#x27;jack&#x27;</span>), (<span class="number">40</span>, <span class="string">&#x27;john&#x27;</span>)]</span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&quot;data.csv&quot;</span>, <span class="string">&quot;w&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    <span class="comment"># 创建csv对象</span></span><br><span class="line">    b_csv = csv.writer(f)</span><br><span class="line">    <span class="comment"># 写入一行（标题）</span></span><br><span class="line">    b_csv.writerow(headers)</span><br><span class="line">    <span class="comment"># 写入多行（数据）</span></span><br><span class="line">    b_csv.writerows(rows)</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line"><span class="comment"># 读取csv文件</span></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&quot;data.csv&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    <span class="comment"># 创建csv对象，他是一个包含所有数据的列表，每一行为一个元素</span></span><br><span class="line">    a_csv = csv.reader(f)</span><br><span class="line">    <span class="comment"># 获得列表对象，它包含标题列的信息</span></span><br><span class="line">    headers = <span class="built_in">next</span>(a_csv)</span><br><span class="line">    <span class="comment"># 循环打印各行内容</span></span><br><span class="line">    <span class="keyword">for</span> row <span class="keyword">in</span> a_csv:</span><br><span class="line">        <span class="built_in">print</span>(row)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="os模块"><a href="#os模块" class="headerlink" title="os模块"></a>os模块</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220086.png" alt="image-20231122135649592"></p>
<p>os模块可以帮助我们直接对操作系统进行操作。我们可以直接调用操作系统的可执行文件、命令，直接操作文件、目录等等。</p>
<blockquote>
<p>:warning:os模块是做系统运维非常重要的基础。</p>
</blockquote>
<h4 id="调用操作系统可执行文件-控制台乱码问题"><a href="#调用操作系统可执行文件-控制台乱码问题" class="headerlink" title="调用操作系统可执行文件-控制台乱码问题"></a>调用操作系统可执行文件-控制台乱码问题</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220087.png" alt="image-20231122140107241"></p>
<p><strong>控制台乱码问题</strong></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220088.png" alt="image-20231122140130581"></p>
<h4 id="获取文件信息-创建和删除文件夹"><a href="#获取文件信息-创建和删除文件夹" class="headerlink" title="获取文件信息-创建和删除文件夹"></a>获取文件信息-创建和删除文件夹</h4><p>我们可以通过前面讲的文件对象实现对于文件内容的读写操作。如果，还需要对文件和目录做其他操作，可以使用<code>os</code>和<code>os.path</code>模块。</p>
<p><strong><code>os</code>模块下常用操作文件的方法</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th>方法名</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>remove(path)</td>
<td>删除指定的文件</td>
</tr>
<tr>
<td>rename(src,dest)</td>
<td>重命名文件或目录</td>
</tr>
<tr>
<td>stat(path)</td>
<td>返回文件的所有属性</td>
</tr>
<tr>
<td>listdir(path)</td>
<td>返回path目录下的文件和目录列表</td>
</tr>
</tbody>
</table>
</div>
<p><code>os</code>模块下关于目录操作的相关方法，汇总如下：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>方法名</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>mkdir(path)</td>
<td>创建目录</td>
</tr>
<tr>
<td>makedirs(path1/path2/path3/…)</td>
<td>创建多级目录</td>
</tr>
<tr>
<td>rmdir(path)</td>
<td>删除目录</td>
</tr>
<tr>
<td>removedirs(path1/path2…)</td>
<td>删除多级目录</td>
</tr>
<tr>
<td>getcwd()</td>
<td>返回当前工作目录：current work dir</td>
</tr>
<tr>
<td>chdir(path)</td>
<td>把path设为当前工作目录</td>
</tr>
<tr>
<td>walk()</td>
<td>遍历目录树</td>
</tr>
<tr>
<td>sep</td>
<td>当前操作系统所使用的路径分隔符</td>
</tr>
</tbody>
</table>
</div>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="comment"># 打印基本信息</span></span><br><span class="line"><span class="built_in">print</span>(os.name)  <span class="comment"># windows--nt  linux--&gt;posix</span></span><br><span class="line"><span class="built_in">print</span>(os.sep)  <span class="comment"># windows--&gt;\  linux--&gt;/</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">repr</span>(os.linesep))  <span class="comment"># windows--&gt;\r\n  linux--&gt;\n</span></span><br><span class="line">a = <span class="string">&#x27;3&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">repr</span>(a))  <span class="comment"># repr可显示数据信息</span></span><br><span class="line"><span class="comment"># 获取文件和文件夹的相关信息</span></span><br><span class="line"><span class="built_in">print</span>(os.stat(<span class="string">&quot;practice.py&quot;</span>))</span><br><span class="line"><span class="comment"># 关于工作目录的操作</span></span><br><span class="line"><span class="built_in">print</span>(os.getcwd())  <span class="comment"># 获取当前工作目录</span></span><br><span class="line">os.chdir(<span class="string">&quot;d:&quot;</span>)  <span class="comment"># 当前工作目录就变成了d: 的根目录</span></span><br><span class="line"><span class="comment"># 创建目录，删除目录</span></span><br><span class="line">os.mkdir(<span class="string">&quot;test&quot;</span>)</span><br><span class="line">os.rmdir(<span class="string">&quot;test&quot;</span>)</span><br><span class="line"><span class="comment"># 创建多级目录</span></span><br><span class="line">os.makedirs(<span class="string">&quot;test1/test2/test3&quot;</span>)</span><br><span class="line"><span class="comment"># 更改目录名字</span></span><br><span class="line">os.rename(<span class="string">&quot;test&quot;</span>, <span class="string">&quot;测试&quot;</span>)</span><br><span class="line"><span class="comment"># 列出子目录</span></span><br><span class="line">dirs = os.listdir(<span class="string">&quot;test1&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(dirs)</span><br></pre></td></tr></table></figure>
<h4 id="os-path模块-常用方法"><a href="#os-path模块-常用方法" class="headerlink" title="os.path模块-常用方法"></a>os.path模块-常用方法</h4><p>os.path模块提供了目录相关（路径判断、路径切分、路径连接、文件夹遍历）的操作</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>isabs(path)</td>
<td>判断path是否绝对路径</td>
</tr>
<tr>
<td>isdir(path)</td>
<td>判断path是否为目录</td>
</tr>
<tr>
<td>isfile(path)</td>
<td>判断path是否为文件</td>
</tr>
<tr>
<td>exists(path)</td>
<td>判断指定路径的文件是否存在</td>
</tr>
<tr>
<td>getsize(filename)</td>
<td>返回文件的大小</td>
</tr>
<tr>
<td>abspath(path)</td>
<td>返回绝对路径</td>
</tr>
<tr>
<td>dirname(p)</td>
<td>返回目录的路径</td>
</tr>
<tr>
<td>getatime(filename)</td>
<td>返回文件的最后访问时间</td>
</tr>
<tr>
<td>getmtime(filename)</td>
<td>返回文件的最后修改时间</td>
</tr>
<tr>
<td>walk(top,func,arg)</td>
<td>递归方式遍历目录</td>
</tr>
<tr>
<td>join(path,*paths)</td>
<td>连接多个path</td>
</tr>
<tr>
<td>split(path)</td>
<td>对路径进行分割，以列表形式返回</td>
</tr>
<tr>
<td>splitext(path)</td>
<td>从路径中分割文件的扩展名</td>
</tr>
</tbody>
</table>
</div>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os.path</span><br><span class="line"></span><br><span class="line">path = os.getcwd()</span><br><span class="line"><span class="comment"># 列出子目录和子文件</span></span><br><span class="line">file_list = os.listdir(path)</span><br><span class="line"><span class="comment"># 只打印以.py结尾的文件名</span></span><br><span class="line"><span class="keyword">for</span> file_name <span class="keyword">in</span> file_list:</span><br><span class="line">    pos = file_name.rfind(<span class="string">&quot;.&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> file_name[pos + <span class="number">1</span>:] == <span class="string">&quot;py&quot;</span>:</span><br><span class="line">        <span class="built_in">print</span>(file_name)</span><br><span class="line">        </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">practice.py</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;*********************************&quot;</span>)</span><br><span class="line"><span class="comment"># 用推导式列出目录下所有的.py文件</span></span><br><span class="line">file_list2 = [file_name <span class="keyword">for</span> file_name <span class="keyword">in</span> os.listdir(path) <span class="keyword">if</span> file_name.endswith(<span class="string">&quot;.py&quot;</span>)]</span><br><span class="line"><span class="built_in">print</span>(file_list2)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">[&#x27;practice.py&#x27;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="使用walk递归遍历所有子目录和子文件"><a href="#使用walk递归遍历所有子目录和子文件" class="headerlink" title="使用walk递归遍历所有子目录和子文件"></a>使用walk递归遍历所有子目录和子文件</h4><p>os.walk()方法是一个简单易用的文件、目录遍历器，可以帮助我们高效的处理文件、目录方面的事情。格式如下：</p>
<p><code>os.walk(top[,topdown=True[,onerror=None[,followlinks=False]]])</code></p>
<p>其中，<code>top</code>:是要遍历的目录。<code>topdown</code>:可选，<code>True</code>, 先遍历<code>top</code>目录再遍历子目录。</p>
<p>返回三元组<code>(root、dirs、files)</code>:</p>
<p><code>root</code>: 当前正在遍历的文件夹本身</p>
<p><code>dirs</code>: 一个列表，该文件夹中所有的目录的名字</p>
<p><code>files</code>: 一个列表，该文件夹中所有的文件的名字</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line">path = os.getcwd()</span><br><span class="line"><span class="comment"># topdown=False:先遍历子目录再遍历top目录</span></span><br><span class="line">list_files = os.walk(path, topdown=<span class="literal">False</span>)</span><br><span class="line"><span class="keyword">for</span> root, dirs, files <span class="keyword">in</span> list_files:</span><br><span class="line">    <span class="keyword">for</span> name <span class="keyword">in</span> files:</span><br><span class="line">        <span class="built_in">print</span>(os.path.join(root, name))</span><br><span class="line">    <span class="keyword">for</span> name <span class="keyword">in</span> dirs:</span><br><span class="line">        <span class="built_in">print</span>(os.path.join(root, name))</span><br></pre></td></tr></table></figure>
<h3 id="shutil模块"><a href="#shutil模块" class="headerlink" title="shutil模块"></a>shutil模块</h3><h4 id="shutil模块（拷贝和压缩）"><a href="#shutil模块（拷贝和压缩）" class="headerlink" title="shutil模块（拷贝和压缩）"></a>shutil模块（拷贝和压缩）</h4><p><code>shutil</code>模块是python<strong>标准库</strong>中提供的，主要用来做文件和文件夹的<strong>拷贝、移动、删除</strong>等；还可以做文件和文件夹的<strong>压缩、解压缩</strong>操作。</p>
<p><code>os</code>模块提供了对目录或文件的一般操作。<code>shutil</code>模块作为补充，提供了移动、复制、压缩、解压等操作，这些os模块都没有提供。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> shutil</span><br><span class="line"></span><br><span class="line">shutil.copyfile(<span class="string">&quot;test.txt&quot;</span>, <span class="string">&quot;test_copy.tet&quot;</span>)</span><br><span class="line"><span class="comment"># 递归拷贝  忽略所有的html,htm文件</span></span><br><span class="line">shutil.copytree(<span class="string">&quot;source&quot;</span>, <span class="string">&quot;destination&quot;</span>, ignore=shutil.ignore_patterns(<span class="string">&quot;*.html&quot;</span>, <span class="string">&quot;*.htm&quot;</span>))</span><br></pre></td></tr></table></figure>
<h4 id="shutil和zipfile模块-压缩和解压缩"><a href="#shutil和zipfile模块-压缩和解压缩" class="headerlink" title="shutil和zipfile模块-压缩和解压缩"></a>shutil和zipfile模块-压缩和解压缩</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> shutil</span><br><span class="line"><span class="keyword">import</span> zipfile</span><br><span class="line"></span><br><span class="line"><span class="comment"># 压缩某个文件</span></span><br><span class="line">shutil.make_archive(<span class="string">&quot;d:/destination&quot;</span>, <span class="string">&quot;zip&quot;</span>, <span class="string">&quot;d:/source&quot;</span>)</span><br><span class="line"><span class="comment"># 压缩：将指定多个文件压缩到一个zip文件</span></span><br><span class="line">z = zipfile.ZipFile(<span class="string">&quot;test.zip&quot;</span>, <span class="string">&quot;w&quot;</span>)</span><br><span class="line">z.write(<span class="string">&quot;a.txt&quot;</span>)</span><br><span class="line">z.write(<span class="string">&quot;b.txt&quot;</span>)</span><br><span class="line">z.write(<span class="string">&quot;c.txt&quot;</span>)</span><br><span class="line">z.close()</span><br><span class="line"><span class="comment"># 解压缩</span></span><br><span class="line">z2 = zipfile.ZipFile(<span class="string">&quot;test.zip&quot;</span>, <span class="string">&quot;r&quot;</span>)</span><br><span class="line"><span class="comment"># 解压到的位置</span></span><br><span class="line">z2.extractall(<span class="string">&quot;d:/&quot;</span>)</span><br><span class="line">z2.close()</span><br></pre></td></tr></table></figure>
<h3 id="递归算法原理-自己复习前面讲过的算法原理"><a href="#递归算法原理-自己复习前面讲过的算法原理" class="headerlink" title="递归算法原理-自己复习前面讲过的算法原理"></a>递归算法原理-自己复习前面讲过的算法原理</h3><h3 id="递归算法-目录树结构的展示"><a href="#递归算法-目录树结构的展示" class="headerlink" title="递归算法-目录树结构的展示"></a>递归算法-目录树结构的展示</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> os.path</span><br><span class="line"></span><br><span class="line"><span class="comment"># 递归遍历目录树</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">my_print_file</span>(<span class="params">path, level</span>):</span><br><span class="line">    child_files = os.listdir(path)</span><br><span class="line">    <span class="keyword">for</span> file <span class="keyword">in</span> child_files:</span><br><span class="line">        file_path = os.path.join(path, file)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;\t&quot;</span> * level + file_path[file_path.rfind(os.sep) + <span class="number">1</span>:])</span><br><span class="line">        <span class="comment"># 如果是文件夹，递归打印</span></span><br><span class="line">        <span class="keyword">if</span> os.path.isdir(file_path):</span><br><span class="line">            my_print_file(file_path, level + <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">my_print_file(<span class="string">&quot;test1&quot;</span>, <span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">test2 </span></span><br><span class="line"><span class="string">	test3</span></span><br><span class="line"><span class="string">		test.txt</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h2 id="模块"><a href="#模块" class="headerlink" title="模块"></a>模块</h2><h3 id="模块化编程理念-什么是模块-哲学思想"><a href="#模块化编程理念-什么是模块-哲学思想" class="headerlink" title="模块化编程理念-什么是模块-哲学思想"></a>模块化编程理念-什么是模块-哲学思想</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220089.png" alt="image-20231123153943364"></p>
<ol>
<li><p>Python程序由模块组成。一个模块对应python源文件，一般后缀名是：<code>.py</code></p>
</li>
<li><p>模块由语句组成。运行Python程序时，按照模块中语句的顺序依次执行</p>
</li>
<li><p>语句是Python程序的构造单元，用于创建对象、变量赋值、调用函数、控制语句等</p>
</li>
</ol>
<p><strong>标准库模块(standard library)</strong></p>
<p>与函数类似，模块也分为标准库模块和用户自定义模块。</p>
<p>Python标准库提供了操作系统功能、网络通信、文本处理、文件处理、数学运算等基本的功能。比如：random(随机数)、math(数学运算)、time(时间处理)、file(文件处理)、os(和操作系统交互)、sys(和解释器交互)等。</p>
<p>另外，Pythor还提供了海量的第三方模块，使用方式和标准库类似。功能覆盖了我们能想象到的所有领域，比如：科学计算、WEB开发、大数据、人工智能、图形系统等。</p>
<p><strong>为什么需要模块化编程</strong></p>
<p>模块(module)对应于Python源代码文件(.py文件)。模块中可以定义变量、函数、类、普通语句。这样，我们可以将一个Pythona程序分解成多个模块，便于后期的重复应用。</p>
<p>模块化编程(Modular Programming)将一个任务分解成多个模块。每个模块就像一个积木一样，便于后期的反复使用、反复搭建。</p>
<p><strong>模块化编程有如下几个重要优势：</strong></p>
<ol>
<li>便于将一个任务分解成多个模块，实现团队协同开发，完成大规模程序</li>
<li>实现代码复用。一个模块实现后，可以被反复调用</li>
<li>可维护性增强</li>
</ol>
<h3 id="模块化编程的流程-设计和实现分离的思想"><a href="#模块化编程的流程-设计和实现分离的思想" class="headerlink" title="模块化编程的流程-设计和实现分离的思想"></a>模块化编程的流程-设计和实现分离的思想</h3><p><strong>模块化编程的流程</strong></p>
<p>模块化编程的一般流程：</p>
<p>①设计API，进行功能描述。</p>
<p>②编码实现API中描述的功能。</p>
<p>③在模块中编写测试代码，并消除全局代码。</p>
<p>④使用私有函数实现不被外部客户端调用的模块函数。</p>
<p><strong>模块的API和功能描述要点</strong></p>
<p>API(Application Programming Interface应用程序编程接口)是用于描述模块中提供的函数和类的功能描述和使用方式描述。</p>
<p>模块化编程中，首先设计的就是模块的AP!(即要实现的功能描述)，然后开始编码实现API中描述的功能。最后，在其他模块中导入本模块进行调用。</p>
<p>可以通过help(模块名)查看模块的API。一般使用时先导入模块然后通过help函数查看。</p>
<p> 【示例】设计计算薪水模块的API</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># encoding=utf-8</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">本模块是用来计算公司员工的薪资</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line">company = <span class="string">&quot;ailbaba&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">yearSalary</span>(<span class="params">monthSalary</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    根据传入的月薪，计算年薪</span></span><br><span class="line"><span class="string">    :param monthSalary: 月薪</span></span><br><span class="line"><span class="string">    :return: 年薪</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">daySalary</span>(<span class="params">monthSalary</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    根据传入的月薪，计算日薪(按照一个月22.5天计算)</span></span><br><span class="line"><span class="string">    :param monthSalary: 月薪</span></span><br><span class="line"><span class="string">    :return: 日薪</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">##################################################################################</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 在别的模块中使用</span></span><br><span class="line"><span class="keyword">import</span> salary</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(salary.__doc__)</span><br><span class="line"><span class="built_in">print</span>(salary.yearSalary.__doc__)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><strong>模块的创建和测试代码</strong></p>
<p>每个模块都有一个名称，通过特殊变量<code>__name__</code>可以获取模块的名称。在正常情况下，模块名字对应源文件名。仅有一个例外，就是当<strong>一个模块被作为程序入口时（主程序、交互式提示符下)</strong>，它的<code>__name__</code>的值为<code>__main__</code>。我们可以根据这个特点，将模块源代码文件中的测试代码进行独立的处理。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># encoding=utf-8</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">本模块是用来计算公司员工的薪资</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line">company = <span class="string">&quot;ailbaba&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">yearSalary</span>(<span class="params">monthSalary</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    根据传入的月薪，计算年薪</span></span><br><span class="line"><span class="string">    :param monthSalary: 月薪</span></span><br><span class="line"><span class="string">    :return: 年薪</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">return</span> monthSalary * <span class="number">12</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">daySalary</span>(<span class="params">monthSalary</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    根据传入的月薪，计算日薪(按照一个月22.5天计算)</span></span><br><span class="line"><span class="string">    :param monthSalary: 月薪</span></span><br><span class="line"><span class="string">    :return: 日薪</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">return</span> monthSalary / <span class="number">22.5</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    <span class="comment"># 这是一个测试</span></span><br><span class="line">    <span class="built_in">print</span>(yearSalary(<span class="number">6000</span>))</span><br></pre></td></tr></table></figure>
<p><strong>模块文档字符串和API设计</strong></p>
<p>我们可以在模块的第一行增加一个文档字符串，用于描述模块的相关功能。然后，通过<code>__doc__</code>可以获得文档字符串的内容。</p>
<h3 id="模块导入-import和from-import详解和区别"><a href="#模块导入-import和from-import详解和区别" class="headerlink" title="模块导入-import和from_import详解和区别"></a>模块导入-import和from_import详解和区别</h3><p>模块化设计的好处之一就是“代码复用性高”。写好的模块可以被反复调用，重复使用。模块的导入就是“在本模块中使用其他模块”。</p>
<p><strong>import语句导入</strong></p>
<p><code>import</code>语句的基本语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> 模块名             <span class="comment"># 导入一个模块</span></span><br><span class="line"><span class="keyword">import</span> 模块<span class="number">1</span>, 模块<span class="number">2</span>       <span class="comment"># 导入多个模块</span></span><br><span class="line"><span class="keyword">import</span> 模块名 <span class="keyword">as</span> 模块名	<span class="comment"># 导入模块并使用新名字</span></span><br></pre></td></tr></table></figure>
<p> <code>import</code>加载的模块分为四种类型：</p>
<ol>
<li>使用python编写的代码<code>.py</code>文件</li>
<li>已被编译为共享库或<code>DLL</code>的C或C++扩展</li>
<li>一组模块的包</li>
<li>使用C编写并链接到python解释器的内置模块</li>
</ol>
<p>我们一般通过<code>import</code>语句实现模块的导入和使用，import本质上是使用了内置函数<code>__import__()</code>。</p>
<p>当我们通过<code>import</code>导入一个模块时，python解释器进行执行，最终会生成一个对象，这个对象就代表了被加载的模块。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># encoding=utf-8</span></span><br><span class="line"><span class="keyword">import</span> math <span class="keyword">as</span> m</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(m))</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(m))</span><br><span class="line"><span class="built_in">print</span>(m.sqrt(<span class="number">4</span>))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">1630061747552</span></span><br><span class="line"><span class="string">&lt;class &#x27;module&#x27;&gt;</span></span><br><span class="line"><span class="string">2.0</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>由上，我们可以看到<code>math</code>模块被加载后，实际会生成一个<code>module</code>类的对象，该对象被<code>math</code>变量引用。我们可以通过<code>math</code>变量引用模块中所有的内容。</p>
<p>我们通过<code>import</code>导入多个模块，本质上也是生成多个<code>module</code>类的对象而已。</p>
<p>有时候，我们也需要给模块起个别名，本质上，这个别名仅仅是新创建一个变量引用加载的模块对象而已。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># encoding=utf-8</span></span><br><span class="line"><span class="keyword">import</span> math <span class="keyword">as</span> m</span><br><span class="line"><span class="keyword">import</span> math</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(m))</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(m))</span><br><span class="line"><span class="built_in">print</span>(m.sqrt(<span class="number">4</span>))</span><br><span class="line"></span><br><span class="line">m2 = math</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(m2))</span><br><span class="line"><span class="built_in">print</span>(m2.sqrt(<span class="number">4</span>))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">1769170820448</span></span><br><span class="line"><span class="string">&lt;class &#x27;module&#x27;&gt;</span></span><br><span class="line"><span class="string">2.0</span></span><br><span class="line"><span class="string">&lt;class &#x27;module&#x27;&gt;</span></span><br><span class="line"><span class="string">2.0</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><strong>from…import导入</strong></p>
<p>Python中可以使用<code>from...import</code>导入<strong>模块中的成员</strong>。基本语法格式如下：</p>
<p><code>from 模块名 import 成员1，成员2，…</code></p>
<p>如果希望导入一个模块中的所有成员，则可以采用如下方式：</p>
<p><code>from 模块名 import *</code></p>
<blockquote>
<p>:warning:尽量避免 <code>from 模块名 import *</code>这种写法。<code>*</code>它表示导入模块中所有的不是以下划线<code>_</code>开头的名字都导入到当前位置。但你不知道你导入什么名字，很有可能会覆盖掉你之前已经定义的名字。而且可读性极其的差。一般生产环境中尽量避免使用，学习时没有关系。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> sqrt, sin</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(sqrt(<span class="number">9</span>))</span><br><span class="line"><span class="built_in">print</span>(sin(<span class="number">1</span>))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">3.0</span></span><br><span class="line"><span class="string">0.479425538604203</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><strong>import语句和from…importi语句的区别</strong></p>
<p><code>import</code>导入的是模块。<code>from...import</code>导入的是<strong>模块中的一个函数/一个类</strong>。</p>
<blockquote>
<p>如果进行类比的话，<code>import</code>导入的是“文件””，我们要使用该“文件”下的内容，必须前面加“文件名称”。<code>from...import</code>导入的是文件下的“内容”，我们直接使用这些内容”即可，前面再也不需要加“文件名称”了。</p>
</blockquote>
<h3 id="import加载底层原理-importlib实现动态导入"><a href="#import加载底层原理-importlib实现动态导入" class="headerlink" title="import加载底层原理-importlib实现动态导入"></a>import加载底层原理-importlib实现动态导入</h3><p><strong><code>__import__()</code>动态导入</strong></p>
<p><code>import</code>语句本质上就是调用内置函数<code>__import__()</code>,我们可以通过它实现动态导入。给<code>__import__()</code>动态传递不同的的参数值，就能导入不同的模块</p>
<p>注意：一般不建议我们自行使用<em>`<em>import</em></em>()<code>导入，其行为在python.2和python.3中有差异，会导致意外错误。如果需要动态导入可以使用</code>importlib`模块</p>
<p><strong>模块的加载问题</strong></p>
<p>当导入一个模块时，模块中的代码都会被执行。不过，如果再次导入这个模块，则不会再次执行。</p>
<p>Python的设计者为什么这么设计？因为，导入模块更多的时候需要的是定义模块中的变量、函数、对象等。这些并不需要反复定义和执行。“只导入一次<code>import-only-once</code>“就成了一种优化。</p>
<blockquote>
<p>一个模块无论导入多少次，这个模块在整个解释器进程内有且仅有一个实例对象。</p>
</blockquote>
<p><strong>重新加载</strong></p>
<p>有时候我们确实需要重新加载一个模块，这时候可以使用：<code>importlib.reload()</code>方法</p>
<h3 id="包的概念-创建包-导入包"><a href="#包的概念-创建包-导入包" class="headerlink" title="包的概念-创建包-导入包"></a>包的概念-创建包-导入包</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220090.png" alt="image-20231123204236853"></p>
<p> 包(package)的概念和结构</p>
<p>当一个项目中有很多个模块时，需要再进行组织。我们将功能类似的模块放到一起，形成了“包”。==本质上，“包”就是一个必须有<code>__init__.py</code>的文件夹==。典型结构如下：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220092.png" alt="image-20231123204807813"></p>
<p>包下面可以包含“模块(module)”,也可以再包含“子包(subpackage)”。就像文件夹下面可以有文件，也可以有子文件夹一样。</p>
<p><strong>Pycharm里建包：</strong></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220093.png" alt="image-20231123204627446"></p>
<p><strong>导入包操作和本质</strong></p>
<p>上一节中的包结构，我们需要导入<code>module_AA.py</code>。方式如下：</p>
<ol>
<li><p><code>import a.aa.module_AA</code></p>
<p>在使用时，必须加完整名称来引用，比如：<code>a.aa.module_AA.fun_AA()</code></p>
</li>
<li><p><code>from a.aa import module_AA</code></p>
<p>在使用时，直接可以使用模块名。比如：<code>module_AA.fun_AA()</code></p>
</li>
<li><p><code>from a.aa.module_AA import fun_AA</code> 直接导入函数</p>
</li>
</ol>
<p>在使用时，直接可以使用函数名。比如：<code>fun_AA()</code></p>
<blockquote>
<ol>
<li><code>from package import item</code>这种语法中，item可以是包、模块，也可以是函数、类、变量。</li>
<li><code>import item1.item2</code>这种语法中，item必须是包或模块，不能是其他。</li>
</ol>
</blockquote>
<p><strong>导入包的本质</strong>其实是“==导入了包的<code>__init__.py</code>“文件==。也就是说，<code>import pack1</code>意味着执行了包<code>pack1</code>下面的<code>__init__.py</code>文件。这样，可以在<code>__init__.py</code>中批量导入我们需要的模块，而不再需要一个个导入。</p>
<p><code>__init__.py</code>的三个核心作用：</p>
<p>①作为包的标识，不能删除。</p>
<p>②导入包实质是执行<code>__init__.py</code>文件，可以在<code>__init__.py</code>文件中做这个<strong>包的初始化、以及需要统一执行代码、批量导入</strong></p>
<blockquote>
<p>如上测试我们可以看出python的设计者非常巧妙的通过<code>__init__.py</code>文件将包转成了模块的操作。</p>
</blockquote>
<h3 id="包的模糊导入"><a href="#包的模糊导入" class="headerlink" title="包的模糊导入"></a>包的模糊导入</h3><p>用<code>*</code>导入包</p>
<p><code>import *</code> 这样的语句理论上是希望文件系统找出包中所有的子模块，然后导入它们。这可能会花长时间等。Python解决方案是提供一个明确的包索引。</p>
<p>这个索引由<code>__init__.py</code>定义<code>__all__</code>变量，该变量为一个列表，如上例<code>a</code>包下的<code>__init__.py</code>中，可定义<code>__all__= [&quot;module_A&quot;,&quot;module_A2&quot;]</code></p>
<p>这意味着，<code>from sound.effects import *</code>会从对应的包中导入以上两个子模块</p>
<blockquote>
<p>:warning:尽管提供<code>import *</code>的方法，仍不建议在生产代码中使用这种写法。</p>
</blockquote>
<h3 id="PIP安装第三方库"><a href="#PIP安装第三方库" class="headerlink" title="PIP安装第三方库"></a>PIP安装第三方库</h3><p><strong>库(Library)</strong></p>
<p>Python中库是借用其他编程语言的概念，没有特别具体的定义。</p>
<p>模块和包侧重于代码组织，有明确的定义。库强调的是功能性，而不是代码组织。</p>
<p>我们通常将某个功能的“模块的集合”，称为库。</p>
<p><strong>标准库(Standard Library)</strong></p>
<p>Python拥有一个强大的标准库。Python语言的核心只包含数字、字符串、列表、字典、文件等常见类型和函数，而由Python标准库提供了系统管理、网络通信、文本处理、数据库接口、图形系统、ML处理等额外的功能。</p>
<p>Python标准库的主要功能有：</p>
<p>①文本处理，包含文本格式化、正则表达式匹配、文本差异计算与合并、Unicode支持，二进制数据处理等功能</p>
<p>②文件处理，包含文件操作、创建临时文件、文件压缩与归档、操作配置文件等功能</p>
<p>③操作系统功能，包含线程与进程支持、IO复用、日期与时间处理、调用系统函数、日志(logging)等功能</p>
<p>④网络通信，包含网络套接字，SSL加密通信、异步网络通信等功能</p>
<p>⑤网络协议，支持HTTP，FTP，SMTP，POP，IMAP，NNTP，XMLRPC等多种网络协议，并提供了编写网络服务器的框架</p>
<p>⑥W3C格式支持，包含HTML，SGML，XML的处理。</p>
<p>⑦其它功能，包括国际化支持、数学运算、HASH、Tkinter等</p>
<blockquote>
<p>目前学过的有：random、math、time、file、os、sys等模块。</p>
<p>①random模块实现随机数处理</p>
<p>②math模块实现数学相关的运算</p>
<p>③time模块实现时间的处理</p>
<p>④file模块实现对文件的操作</p>
<p>⑤os模块实现和操作系统的交互</p>
<p>⑥sys模块实现和解释器的交互</p>
</blockquote>
<p><strong>PIP模块管理工具</strong></p>
<p>pip是一个现代的，通用的Python包管理工具。提供了对Python包的查找、下载、安装、卸载的功能。</p>
<p><strong>安装第三方扩展库的2种方式</strong></p>
<p>第三方库有数十万种之多，以pymysql库为例讲解第三方扩展库的安装。</p>
<p><strong>第一种方式：命令行下远程安装</strong></p>
<p>以安装第三方pymysql库为例，在命令行提示符下输入：<code>pip install pymysql</code>即可。</p>
<p><strong>第二种方式：Pycharm中直接安装到项目中</strong></p>
<p>在Pycharm中，依次点击：<code>file-&gt;setting-&gt;Project 本项目名-&gt;Project Interpreter</code></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220094.png" alt="image-20231123211713736"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311232220095.png" alt="image-20231123211743087"></p>
<h2 id="GUI编程"><a href="#GUI编程" class="headerlink" title="GUI编程"></a>GUI编程</h2><h3 id="GUI编程和tkinter介绍-第一个GUI程序"><a href="#GUI编程和tkinter介绍-第一个GUI程序" class="headerlink" title="GUI编程和tkinter介绍-第一个GUI程序"></a>GUI编程和tkinter介绍-第一个GUI程序</h3><p>我们前面实现的都是基于控制台的程序，程序和用户的交互通过控制台来完成。</p>
<p>本章，我们将学习 GUI（Graphics User Interface），即<strong>图形用户界面编程</strong>，我们可以通过 python 提供的丰富的组件，快速的实现使用图形界面和用户交互。</p>
<p>GUI 编程类似于“搭积木”，将一个个组件(Widget)放到窗口中。如下是 windows 中的画图软件，就是一个典型的 GUI 程序</p>
<p><strong>常用的 GUI 库</strong></p>
<ol>
<li><p>Tkinter</p>
<p>tkinter（Tk interface）是 Python 的标准 GUI 库，支持跨平台的 GUI 程序开发。tkinter适合小型的 GUI 程序编写，也特别适合初学者学习 GUI 编程。本书以 tkinter 为核心进行讲解。</p>
</li>
<li><p>wxPython</p>
<p>wxPython 是比较流行的 GUI 库，适合大型应用程序开发，功能强于 tkinter，整体设计框架类似于 MFC(Microsoft Foundation Classes 微软基础类库)。</p>
</li>
<li><p>PyQT</p>
</li>
</ol>
<p>Qt 是一种开源的 GUI 库，适合大型 GUI 程序开发，PyQT 是 Qt 工具包标准的 Python 实现。我们也可以使用 Qt Desginer 界面设计器快速开发 GUI 应用程序。</p>
<p><strong>基于 tkinter 模块创建 GUI 程序包含如下 4 个核心步骤：</strong></p>
<ol>
<li>创建应用程序主窗口对象（也称：根窗口）</li>
<li>在主窗口中，添加各种可视化组件，比如：按钮（Button）、文本框（Label）等。</li>
<li>通过几何布局管理器，管理组件的大小和位置</li>
<li>事件处理</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"></span><br><span class="line"><span class="comment"># 1.创建应用程序主窗口对象（也称：根窗口）</span></span><br><span class="line">root = Tk()</span><br><span class="line"><span class="comment"># 2.在主窗口中，添加各种可视化组件，比如：按钮（Button）、文本框（Label）等。</span></span><br><span class="line">btn01 = Button(root)</span><br><span class="line">btn01[<span class="string">&quot;text&quot;</span>] = <span class="string">&quot;点击送花&quot;</span></span><br><span class="line"><span class="comment"># 3.通过几何布局管理器，管理组件的大小和位置</span></span><br><span class="line">btn01.pack()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 4.事件处理</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">songhua</span>(<span class="params">e</span>):  <span class="comment"># e就是事件对象</span></span><br><span class="line">    messagebox.showinfo(<span class="string">&quot;Message&quot;</span>, <span class="string">&quot;送你花&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;送花&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">btn01.bind(<span class="string">&quot;&lt;Button-1&gt;&quot;</span>, songhua)</span><br><span class="line"></span><br><span class="line">root.mainloop()  <span class="comment"># 调用组件的mainloop()方法，进入事件循环</span></span><br></pre></td></tr></table></figure>
<h3 id="PEP8编码规范-窗口大小和位置"><a href="#PEP8编码规范-窗口大小和位置" class="headerlink" title="PEP8编码规范-窗口大小和位置"></a>PEP8编码规范-窗口大小和位置</h3><p><strong>主窗口位置和大小</strong></p>
<p>通过 <code>geometry(&#39;wxh±x±y&#39;)</code>进行设置。<code>w</code> 为宽度，<code>h</code> 为高度。<code>+x</code> 表示距屏幕左边的距离；<code>-x</code> 表示距屏幕右边的距离；<code>+y</code> 表示距屏幕上边的距离；<code>-y</code> 表示距屏幕下边的距离。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.title(<span class="string">&quot;测试主窗口的位置和大小&quot;</span>)</span><br><span class="line">root.geometry(<span class="string">&quot;500x400+100+200&quot;</span>)  <span class="comment"># 宽度 500，高度 400；距屏幕左边 100，距屏幕上边200</span></span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<h3 id="GUI编程整体描述-常用组件汇总"><a href="#GUI编程整体描述-常用组件汇总" class="headerlink" title="GUI编程整体描述-常用组件汇总"></a>GUI编程整体描述-常用组件汇总</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113910.png" alt="image-20231124174304488"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113911.png" alt="image-20231124174456418">                                                                                            </p>
<p>​                                                                                        <strong>常用组件汇总列表</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th><strong>Tkinter 类</strong></th>
<th style="text-align:center"><strong>名称</strong></th>
<th><strong>简介</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>Toplevel</td>
<td style="text-align:center">顶层</td>
<td>容器类，可用于为其他组件提供单独的容器；Toplevel 有点类似于窗口</td>
</tr>
<tr>
<td>Button</td>
<td style="text-align:center">按钮</td>
<td>代表按钮组件</td>
</tr>
<tr>
<td>Canvas</td>
<td style="text-align:center">画布</td>
<td>提供绘图功能，包括直线、矩形、椭圆、多边形、位图等</td>
</tr>
<tr>
<td>Checkbutton</td>
<td style="text-align:center">复选框</td>
<td>可供用户勾选的复选框</td>
</tr>
<tr>
<td>Entry</td>
<td style="text-align:center">单行输入框</td>
<td>用户可输入内容</td>
</tr>
<tr>
<td>Frame</td>
<td style="text-align:center">容器</td>
<td>用于装载其它 GUI 组件</td>
</tr>
<tr>
<td>Label</td>
<td style="text-align:center">标签</td>
<td>用于显示不可编辑的文本或图标</td>
</tr>
<tr>
<td>LabelFrame</td>
<td style="text-align:center">容器</td>
<td>也是容器组件，类似于 Frame，但它支持添加标题</td>
</tr>
<tr>
<td>Listbox</td>
<td style="text-align:center">列表框</td>
<td>列出多个选项，供用户选择</td>
</tr>
<tr>
<td>Menu</td>
<td style="text-align:center">菜单</td>
<td>菜单组件</td>
</tr>
<tr>
<td>Menubutton</td>
<td style="text-align:center">菜单按钮</td>
<td>用来包含菜单的按钮（包括下拉式、层叠式等）</td>
</tr>
<tr>
<td>OptionMenu</td>
<td style="text-align:center">菜单按钮</td>
<td>Menubutton 的子类，也代表菜单按钮，可通过按钮打开一个菜单</td>
</tr>
<tr>
<td>Message</td>
<td style="text-align:center">消息框</td>
<td>类似于标签，但可以显示多行文本；后来当 Label 也能显示多行文本之后，该组件基本处于废弃状态</td>
</tr>
<tr>
<td>PanedWindow</td>
<td style="text-align:center">分区窗口</td>
<td>该容器会被划分成多个区域，每添加一个组件占一个区域，用户可通过拖动分隔线来改变各区域的大小</td>
</tr>
<tr>
<td>Radiobutton</td>
<td style="text-align:center">单选钮</td>
<td>可供用户点边的单选钮</td>
</tr>
<tr>
<td>Scale</td>
<td style="text-align:center">滑动条</td>
<td>拖动滑块可设定起始值和结束值，可显示当前位置的精确值</td>
</tr>
<tr>
<td>Spinbox</td>
<td style="text-align:center">微调选择器</td>
<td>用户可通过该组件的向上、向下箭头选择不同的值</td>
</tr>
<tr>
<td>Scrollbar</td>
<td style="text-align:center">滚动条</td>
<td>用于为组件（文本域、画布、列表框、文本框）提供滚动功能</td>
</tr>
<tr>
<td>Text</td>
<td style="text-align:center">多行文本框</td>
<td>显示多行文本</td>
</tr>
</tbody>
</table>
</div>
<h3 id="GUI程序的经典面向对象写法"><a href="#GUI程序的经典面向对象写法" class="headerlink" title="GUI程序的经典面向对象写法"></a>GUI程序的经典面向对象写法</h3><p>本节程序也是 GUI 应用程序编写的一个主要结构，采用了==面向对象==的方式，更加合理的组织代码。</p>
<p>通过类 <code>Application</code> 组织整个 GUI 程序，类 <code>Application</code> 继承了 <code>Frame</code> 及通过继承拥有了父类的特性。通过构造函数<code>__init__()</code>初始化窗口中的对象，通过 <code>createWidgets()</code>方法创建窗口中的对象。</p>
<p><code>Frame</code> 框架是一个 <code>tkinter</code> 组件，表示一个矩形的区域。<code>Frame</code> 一般作为容器使用，可以放置其他组件，从而实现复杂的布局。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;测试一个经典的GUI程序的写法，使用面向对象的方式&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;一个经典的GUI程序类的写法&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master</span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        <span class="comment"># 几何布局管理器，管理组件的大小和位置</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;创建组件&quot;&quot;&quot;</span></span><br><span class="line">        self.btn01 = Button(self)</span><br><span class="line">        self.btn01[<span class="string">&quot;text&quot;</span>] = <span class="string">&quot;点击送花&quot;</span></span><br><span class="line">        self.btn01.pack()</span><br><span class="line">        self.btn01[<span class="string">&quot;command&quot;</span>] = self.songhua</span><br><span class="line">        <span class="comment"># 创建一个退出按钮</span></span><br><span class="line">        self.btnQuit = Button(self, text=<span class="string">&quot;退出&quot;</span>, command=root.destroy)</span><br><span class="line">        <span class="comment"># 将组件放入application里</span></span><br><span class="line">        self.btnQuit.pack()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">songhua</span>(<span class="params">self</span>):</span><br><span class="line">        messagebox.showinfo(<span class="string">&quot;送花&quot;</span>, <span class="string">&quot;送你花&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x100+200+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;一个经典的GUI程序类的测试&quot;</span>)</span><br><span class="line">    app = Application(master=<span class="literal">None</span>)</span><br><span class="line"></span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113912.png" alt="image-20231124220642885" style="zoom:50%;" /></p>
<h3 id="简单组件"><a href="#简单组件" class="headerlink" title="简单组件"></a>简单组件</h3><h4 id="Label标签-tkinter中图像正确显示全局变量写法"><a href="#Label标签-tkinter中图像正确显示全局变量写法" class="headerlink" title="Label标签-tkinter中图像正确显示全局变量写法"></a>Label标签-tkinter中图像正确显示全局变量写法</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;一个经典的GUI程序类的写法&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master</span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        <span class="comment"># 几何布局管理器，管理组件的大小和位置</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;创建组件&quot;&quot;&quot;</span></span><br><span class="line">        self.label01 = Label(self, text=<span class="string">&quot;label test&quot;</span>, width=<span class="number">10</span>, height=<span class="number">2</span>,</span><br><span class="line">                             bg=<span class="string">&quot;black&quot;</span>, fg=<span class="string">&quot;white&quot;</span>)</span><br><span class="line">        self.label01.pack()</span><br><span class="line">        <span class="comment"># 设置字体</span></span><br><span class="line">        self.label02 = Label(self, text=<span class="string">&quot;字体测试&quot;</span>, width=<span class="number">10</span>, height=<span class="number">2</span>,</span><br><span class="line">                             bg=<span class="string">&quot;blue&quot;</span>, fg=<span class="string">&quot;white&quot;</span>, font=(<span class="string">&quot;黑体&quot;</span>, <span class="number">10</span>))</span><br><span class="line">        self.label02.pack()</span><br><span class="line">        <span class="comment"># 显示图片</span></span><br><span class="line">        <span class="keyword">global</span> photo   <span class="comment"># photo声明为全局变量，如果是局部变量，本方法执行完毕后，图像对象会被销毁，窗口显示不出图像</span></span><br><span class="line">        photo = PhotoImage(file=<span class="string">&quot;../images/logo.gif&quot;</span>)</span><br><span class="line">        self.label03 = Label(self, image=photo)</span><br><span class="line">        self.label03.pack()</span><br><span class="line">        <span class="comment"># 显示多行文本</span></span><br><span class="line">        self.label04 = Label(self, text=<span class="string">&quot;这是第一行\n这是第二行\n这是第三行\n&quot;</span>,</span><br><span class="line">                             borderwidth=<span class="number">1</span>, relief=<span class="string">&quot;solid&quot;</span>, justify=<span class="string">&quot;center&quot;</span>)</span><br><span class="line">        self.label04.pack()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x250+500+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;Label的测试&quot;</span>)</span><br><span class="line">    app = Application(master=<span class="literal">None</span>)</span><br><span class="line"></span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113914.png" alt="image-20231130152234046"></p>
<h4 id="Options选项详解-底层源码分析和阅读-可变参数和运算符重载复习"><a href="#Options选项详解-底层源码分析和阅读-可变参数和运算符重载复习" class="headerlink" title="Options选项详解-底层源码分析和阅读-可变参数和运算符重载复习"></a>Options选项详解-底层源码分析和阅读-可变参数和运算符重载复习</h4><p>通过学习 Label 组件，我们发现可以通过 Options 设置组件的属性，从而控制组件的各种状态。比如：宽度、高度、颜色、位置等等。</p>
<p>我们可以通过三种方式设置 Options 选项，这在各种 GUI 组件中用法都一致。</p>
<ol>
<li><p>创建对象时，使用可变参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fred = Button(self, fg=<span class="string">&quot;red&quot;</span>, bg=<span class="string">&quot;blue&quot;</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>创建对象后，使用字典索引方式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">fred[<span class="string">&quot;fg&quot;</span>] = <span class="string">&quot;red&quot;</span></span><br><span class="line">fred[<span class="string">&quot;bg&quot;</span>] = <span class="string">&quot;blue&quot;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>创建对象后，使用 config()方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fred.config(fg=<span class="string">&quot;red&quot;</span>, bg=<span class="string">&quot;blue&quot;</span>)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="Button-anchor位置控制"><a href="#Button-anchor位置控制" class="headerlink" title="Button-anchor位置控制"></a>Button-anchor位置控制</h4><p>Button（按钮）用来执行用户的单击操作。Button 可以包含文本，也可以包含图像。按钮被单击后会自动调用对应事件绑定的方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;一个经典的GUI程序类的写法&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master</span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        <span class="comment"># 几何布局管理器，管理组件的大小和位置</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;创建组件&quot;&quot;&quot;</span></span><br><span class="line">        self.btn01 = Button(root, text=<span class="string">&quot;登录&quot;</span>, anchor=E, command=self.login)  <span class="comment"># anchor控制字体位置</span></span><br><span class="line">        self.btn01.pack()</span><br><span class="line">        <span class="comment"># 显示图片</span></span><br><span class="line">        <span class="keyword">global</span> photo   <span class="comment"># photo声明为全局变量，如果是局部变量，本方法执行完毕后，图像对象会被销毁，窗口显示不出图像</span></span><br><span class="line">        photo = PhotoImage(file=<span class="string">&quot;../images/start.gif&quot;</span>)</span><br><span class="line">        self.btn02 = Button(root, image=photo, command=self.login)</span><br><span class="line">        self.btn02.pack()</span><br><span class="line">        self.btn02.config(state=<span class="string">&quot;disabled&quot;</span>)  <span class="comment"># 设置按钮为禁用</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">login</span>(<span class="params">self</span>):</span><br><span class="line">        messagebox.showinfo(<span class="string">&quot;登陆成功&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x250+500+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;Button的测试&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line"></span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="Entry单行文本框-StringVar-登录界面设计和功实现"><a href="#Entry单行文本框-StringVar-登录界面设计和功实现" class="headerlink" title="Entry单行文本框-StringVar-登录界面设计和功实现"></a>Entry单行文本框-StringVar-登录界面设计和功实现</h4><p>Entry 用来接收一行字符串的控件。如果用户输入的文字长度长于 Entry 控件的宽度时, 文字会自动向后滚动。如果想输入多行文本, 需要使用 Text 控件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;一个经典的GUI程序类的写法&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master</span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        <span class="comment"># 几何布局管理器，管理组件的大小和位置</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;创建组件&quot;&quot;&quot;</span></span><br><span class="line">        self.label01 = Label(self, text=<span class="string">&quot;用户名&quot;</span>)</span><br><span class="line">        self.label01.pack()</span><br><span class="line"></span><br><span class="line">        <span class="comment"># StringVar变量绑定到指定的组件</span></span><br><span class="line">        <span class="comment"># StringVar变量的值发生变化，组件内容也发生变化</span></span><br><span class="line">        <span class="comment"># 组件内容发生变化，StringVar变量的值也发生变化</span></span><br><span class="line">        username = StringVar()</span><br><span class="line">        self.entry01 = Entry(self, textvariable=username)</span><br><span class="line">        self.entry01.pack()</span><br><span class="line">        username.<span class="built_in">set</span>(<span class="string">&quot;admin&quot;</span>)</span><br><span class="line">        <span class="built_in">print</span>(username.get())       <span class="comment"># admin</span></span><br><span class="line">        <span class="built_in">print</span>(self.entry01.get())   <span class="comment"># admin</span></span><br><span class="line"></span><br><span class="line">        password = StringVar()</span><br><span class="line">        self.entry02 = Entry(self, textvariable=password, show=<span class="string">&quot;*&quot;</span>)  <span class="comment"># 密码以*显示</span></span><br><span class="line">        self.entry02.pack()</span><br><span class="line"></span><br><span class="line">        Button(root, text=<span class="string">&quot;登录&quot;</span>, anchor=E, command=self.login).pack()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">login</span>(<span class="params">self</span>):</span><br><span class="line">        username = self.entry01.get()</span><br><span class="line">        password = self.entry02.get()</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;去数据库对比用户名密码&quot;</span>)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;用户名：&quot;</span> + username)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;密码：&quot;</span> + password)</span><br><span class="line">        <span class="keyword">if</span> username == <span class="string">&quot;admin&quot;</span> <span class="keyword">and</span> password == <span class="string">&quot;123456&quot;</span>:</span><br><span class="line">            messagebox.showinfo(<span class="string">&quot;登录系统&quot;</span>, <span class="string">&quot;登陆成功&quot;</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            messagebox.showinfo(<span class="string">&quot;登录系统&quot;</span>, <span class="string">&quot;登陆失败，用户名或密码错误&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x250+500+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;Entry 的测试&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line"></span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113915.png" alt="image-20231130161750672"></p>
<h4 id="Text多行文本框详解-复杂tag标记"><a href="#Text多行文本框详解-复杂tag标记" class="headerlink" title="Text多行文本框详解-复杂tag标记"></a>Text多行文本框详解-复杂tag标记</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;测试 Text 多行文本框组件的基本用法，使用面向对象的方式&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">import</span> webbrowser</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 宽度 20 个字母(10 个汉字)，高度一个行高</span></span><br><span class="line">        self.w1 = Text(root, width=<span class="number">40</span>, height=<span class="number">12</span>, bg=<span class="string">&quot;gray&quot;</span>)</span><br><span class="line">        self.w1.pack()</span><br><span class="line">        self.w1.insert(<span class="number">1.0</span>, <span class="string">&quot;0123456789\nabcdefg&quot;</span>)  <span class="comment"># 1.0 第一行第一列  行号以 1 开始 列号以 0 开始</span></span><br><span class="line">        self.w1.insert(<span class="number">2.3</span>, <span class="string">&quot;锄禾日当午，汗滴禾下土。谁知盘中餐，粒粒皆辛苦\n&quot;</span>)</span><br><span class="line"></span><br><span class="line">        Button(self, text=<span class="string">&quot;重复插入文本&quot;</span>, command=self.insertText).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        Button(self, text=<span class="string">&quot;返回文本&quot;</span>, command=self.returnText).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        Button(self, text=<span class="string">&quot;添加图片&quot;</span>, command=self.addImage).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        Button(self, text=<span class="string">&quot;添加组件&quot;</span>, command=self.addWidget).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        Button(self, text=<span class="string">&quot;通过 tag 精确控制文本&quot;</span>, command=self.testTag).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">insertText</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># INSERT 索引表示在光标处插入</span></span><br><span class="line">        self.w1.insert(INSERT, <span class="string">&#x27; Gaoqi &#x27;</span>)</span><br><span class="line">        <span class="comment"># END 索引号表示在最后插入</span></span><br><span class="line">        self.w1.insert(END, <span class="string">&#x27;[sxt]&#x27;</span>)</span><br><span class="line">        self.w1.insert(<span class="number">1.8</span>, <span class="string">&quot;gaoqi&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">returnText</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># Indexes(索引)是用来指向 Text 组件中文本的位置，Text 的组件索引也是对应实际字符之间的位置。</span></span><br><span class="line">        <span class="comment"># 核心：行号以 1 开始 列号以 0 开始</span></span><br><span class="line">        <span class="built_in">print</span>(self.w1.get(<span class="number">1.2</span>, <span class="number">1.6</span>))</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;所有文本内容：\n&quot;</span> + self.w1.get(<span class="number">1.0</span>, END))</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addImage</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># global photo</span></span><br><span class="line">        self.photo = PhotoImage(file=<span class="string">&quot;../images/logo.gif&quot;</span>)</span><br><span class="line">        self.w1.image_create(END, image=self.photo)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addWidget</span>(<span class="params">self</span>):</span><br><span class="line">        b1 = Button(self.w1, text=<span class="string">&#x27;爱尚学堂&#x27;</span>)</span><br><span class="line">        <span class="comment"># 在 text 创建组件的命令</span></span><br><span class="line">        self.w1.window_create(INSERT, window=b1)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">testTag</span>(<span class="params">self</span>):</span><br><span class="line">        self.w1.delete(<span class="number">1.0</span>, END)</span><br><span class="line">        self.w1.insert(INSERT, <span class="string">&quot;good good study,day day up!\n 北京尚学堂\n 百战程序员\n百度，搜一下就知道&quot;</span>)</span><br><span class="line">        self.w1.tag_add(<span class="string">&quot;good&quot;</span>, <span class="number">1.0</span>, <span class="number">1.9</span>)</span><br><span class="line">        self.w1.tag_config(<span class="string">&quot;good&quot;</span>, background=<span class="string">&quot;yellow&quot;</span>, foreground=<span class="string">&quot;red&quot;</span>)  <span class="comment"># 改变tag的背景，字体颜色</span></span><br><span class="line">        self.w1.tag_add(<span class="string">&quot;baidu&quot;</span>, <span class="number">4.0</span>, <span class="number">4.2</span>)</span><br><span class="line">        self.w1.tag_config(<span class="string">&quot;baidu&quot;</span>, underline=<span class="literal">True</span>)  <span class="comment"># tag加下划线</span></span><br><span class="line">        self.w1.tag_bind(<span class="string">&quot;baidu&quot;</span>, <span class="string">&quot;&lt;Button-1&gt;&quot;</span>, self.webshow)  <span class="comment"># tag绑定事件</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">webshow</span>(<span class="params">self, event</span>):</span><br><span class="line">        webbrowser.<span class="built_in">open</span>(<span class="string">&quot;http://www.baidu.com&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;450x300+200+300&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<blockquote>
<p><strong>利用 Tags 实现更加强大的文本显示和控制</strong></p>
<p>Tags 通常用于改变 Text 组件中内容的样式和功能。你可以修改文本的字体、尺寸和颜色。另外，Tags 还允许你将文本、嵌入的组件和图片与鼠标和键盘等事件相关联。</p>
</blockquote>
<h4 id="Radiobutton单选按钮"><a href="#Radiobutton单选按钮" class="headerlink" title="Radiobutton单选按钮"></a>Radiobutton单选按钮</h4><p><strong>Radiobutton 控件用于选择同一组单选按钮中的一个。Radiobutton 可以显示文本，也可以显示图像。</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;测试 Radiobutton 组件的基本用法，使用面向对象的方式&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)   <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        self.v = StringVar()</span><br><span class="line">        self.v.<span class="built_in">set</span>(<span class="string">&quot;F&quot;</span>)</span><br><span class="line">        self.r1 = Radiobutton(self, text=<span class="string">&quot;男性&quot;</span>, value=<span class="string">&quot;M&quot;</span>, variable=self.v)</span><br><span class="line">        self.r2 = Radiobutton(self, text=<span class="string">&quot;女性&quot;</span>, value=<span class="string">&quot;F&quot;</span>, variable=self.v)</span><br><span class="line">        self.r1.pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        self.r2.pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        Button(self, text=<span class="string">&quot;确定&quot;</span>, command=self.confirm).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">confirm</span>(<span class="params">self</span>):</span><br><span class="line">        messagebox.showinfo(<span class="string">&quot;测试&quot;</span>, <span class="string">&quot;选择的性别:&quot;</span> + self.v.get())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x50+200+300&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="Checkbutton复选按钮"><a href="#Checkbutton复选按钮" class="headerlink" title="Checkbutton复选按钮"></a>Checkbutton复选按钮</h4><p><strong>Checkbutton 控件用于选择多个按钮的情况。Checkbutton 可以显示文本，也可以显示图像。</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;测试 Checkbutton 组件的基本用法，使用面向对象的方式&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        self.codeHobby = IntVar()</span><br><span class="line">        self.videoHobby = IntVar()</span><br><span class="line">        <span class="built_in">print</span>(self.codeHobby.get())  <span class="comment"># 默认值是 0</span></span><br><span class="line">        self.c1 = Checkbutton(self, text=<span class="string">&quot;敲代码&quot;</span>, variable=self.codeHobby, onvalue=<span class="number">1</span>, offvalue=<span class="number">0</span>)</span><br><span class="line">        self.c2 = Checkbutton(self, text=<span class="string">&quot;看视频&quot;</span>, variable=self.videoHobby, onvalue=<span class="number">1</span>, offvalue=<span class="number">0</span>)</span><br><span class="line">        self.c1.pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        self.c2.pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">        Button(self, text=<span class="string">&quot;确定&quot;</span>, command=self.confirm).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">confirm</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> self.videoHobby.get() == <span class="number">1</span>:</span><br><span class="line">            messagebox.showinfo(<span class="string">&quot;测试&quot;</span>, <span class="string">&quot;看视频，都是正常人有的爱好！你喜欢看什么类型？&quot;</span>)</span><br><span class="line">        <span class="keyword">if</span> self.codeHobby.get() == <span class="number">1</span>:</span><br><span class="line">            messagebox.showinfo(<span class="string">&quot;测试&quot;</span>, <span class="string">&quot;抓获野生程序猿一只，赶紧送给他尚学堂的视频充饥&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x50+200+300&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<h4 id="Canvasl画布组件"><a href="#Canvasl画布组件" class="headerlink" title="Canvasl画布组件"></a>Canvasl画布组件</h4><p>canvas（画布）是一个矩形区域，可以放置图形、图像、组件等。本节我们简单介绍canvas 的使用，更加详细和深入的内容将在后面的“图形绘制”章节讲解。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;测试 Canvas 组件的基本用法，使用面向对象的方式&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        self.canvas = Canvas(self, width=<span class="number">300</span>, height=<span class="number">200</span>, bg=<span class="string">&quot;green&quot;</span>)</span><br><span class="line">        self.canvas.pack()</span><br><span class="line">        <span class="comment"># 画一条直线</span></span><br><span class="line">        line = self.canvas.create_line(<span class="number">10</span>, <span class="number">10</span>, <span class="number">30</span>, <span class="number">20</span>, <span class="number">40</span>, <span class="number">50</span>)  <span class="comment"># 三个点 (x, y)</span></span><br><span class="line">        <span class="comment"># 画一个矩形.</span></span><br><span class="line">        rect = self.canvas.create_rectangle(<span class="number">50</span>, <span class="number">50</span>, <span class="number">100</span>, <span class="number">100</span>)  <span class="comment"># 对角坐标，左上角和右下角坐标</span></span><br><span class="line">        <span class="comment"># 画一个椭圆.坐标两双。为椭圆的外切矩形左上角和底部右下角</span></span><br><span class="line">        oval = self.canvas.create_oval(<span class="number">50</span>, <span class="number">50</span>, <span class="number">100</span>, <span class="number">100</span>)</span><br><span class="line">        <span class="keyword">global</span> photo</span><br><span class="line">        photo = PhotoImage(file=<span class="string">&quot;../images/logo.gif&quot;</span>)</span><br><span class="line">        self.canvas.create_image(<span class="number">150</span>, <span class="number">170</span>, image=photo)</span><br><span class="line">        Button(self, text=<span class="string">&quot;画 10 个矩形&quot;</span>, command=self.draw50Recg).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw50Recg</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, <span class="number">10</span>):</span><br><span class="line">            <span class="comment"># 左上角坐标</span></span><br><span class="line">            x1 = random.randrange(<span class="built_in">int</span>(self.canvas[<span class="string">&quot;width&quot;</span>]) / <span class="number">2</span>)</span><br><span class="line">            y1 = random.randrange(<span class="built_in">int</span>(self.canvas[<span class="string">&quot;height&quot;</span>]) / <span class="number">2</span>)</span><br><span class="line">            <span class="comment"># 右下角坐标</span></span><br><span class="line">            x2 = x1 + random.randrange(<span class="built_in">int</span>(self.canvas[<span class="string">&quot;width&quot;</span>]) / <span class="number">2</span>)</span><br><span class="line">            y2 = y1 + random.randrange(<span class="built_in">int</span>(self.canvas[<span class="string">&quot;height&quot;</span>]) / <span class="number">2</span>)</span><br><span class="line">            self.canvas.create_rectangle(x1, y1, x2, y2)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x300+200+300&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="布局管理器"><a href="#布局管理器" class="headerlink" title="布局管理器"></a>布局管理器</h3><p>一个 GUI 应用程序必然有大量的组件，这些组件如何排布？这时候，就需要使用 tkinter提供的布局管理器帮助我们组织、管理在父组件中子组件的布局方式。tkinter 提供了三种管理器：<code>pack</code>、<code>grid</code>、<code>place</code>。</p>
<h4 id="Grid布局管理器详解"><a href="#Grid布局管理器详解" class="headerlink" title="Grid布局管理器详解"></a>Grid布局管理器详解</h4><p>grid 表格布局，采用==表格结构==组织组件。子组件的位置由行和列的单元格来确定，并且可以跨行和跨列，从而实现复杂的布局。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113916.png" alt="image-20231208162956284"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;测试 Grid 布局管理器的基本用法，使用面向对象的方式&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;通过 grid 布局实现登录界面&quot;&quot;&quot;</span></span><br><span class="line">        self.label01 = Label(self, text=<span class="string">&quot;用户名&quot;</span>)</span><br><span class="line">        self.label01.grid(row=<span class="number">0</span>, column=<span class="number">0</span>)</span><br><span class="line">        self.entry01 = Entry(self)</span><br><span class="line">        self.entry01.grid(row=<span class="number">0</span>, column=<span class="number">1</span>)</span><br><span class="line">        Label(self, text=<span class="string">&quot;用户名为手机号&quot;</span>).grid(row=<span class="number">0</span>, column=<span class="number">2</span>)</span><br><span class="line">        Label(self, text=<span class="string">&quot;密码&quot;</span>).grid(row=<span class="number">1</span>, column=<span class="number">0</span>)</span><br><span class="line">        Entry(self, show=<span class="string">&quot;*&quot;</span>).grid(row=<span class="number">1</span>, column=<span class="number">1</span>)</span><br><span class="line">        Button(self, text=<span class="string">&quot;登录&quot;</span>).grid(row=<span class="number">2</span>, column=<span class="number">1</span>, sticky=EW)  <span class="comment"># 东西两边对齐，拉长</span></span><br><span class="line">        Button(self, text=<span class="string">&quot;取消&quot;</span>).grid(row=<span class="number">2</span>, column=<span class="number">2</span>, sticky=E)   <span class="comment"># 东边对齐</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;400x90+200+300&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="计算器软件界面的设计"><a href="#计算器软件界面的设计" class="headerlink" title="计算器软件界面的设计"></a>计算器软件界面的设计</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;计算器软件界面的设计&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> messagebox</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)    <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;通过 grid 布局实现计算器软件的界面&quot;&quot;&quot;</span></span><br><span class="line">        btnText = ((<span class="string">&quot;MC&quot;</span>, <span class="string">&quot;M+&quot;</span>, <span class="string">&quot;M-&quot;</span>, <span class="string">&quot;MR&quot;</span>),</span><br><span class="line">                   (<span class="string">&quot;C&quot;</span>, <span class="string">&quot;±&quot;</span>, <span class="string">&quot;/&quot;</span>, <span class="string">&quot;✖&quot;</span>),</span><br><span class="line">                   (<span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="string">&quot;-&quot;</span>),</span><br><span class="line">                   (<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="string">&quot;+&quot;</span>),</span><br><span class="line">                   (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="string">&quot;=&quot;</span>),</span><br><span class="line">                   (<span class="number">0</span>, <span class="string">&quot;.&quot;</span>))</span><br><span class="line">        Entry(self).grid(row=<span class="number">0</span>, column=<span class="number">0</span>, columnspan=<span class="number">4</span>, pady=<span class="number">10</span>)</span><br><span class="line">        <span class="keyword">for</span> rindex, r <span class="keyword">in</span> <span class="built_in">enumerate</span>(btnText):</span><br><span class="line">            <span class="keyword">for</span> cindex, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(r):</span><br><span class="line">                <span class="keyword">if</span> c == <span class="string">&quot;=&quot;</span>:                      <span class="comment"># rowspan跨行，columnspan跨列</span></span><br><span class="line">                    Button(self, text=c, width=<span class="number">2</span>)\</span><br><span class="line">                        .grid(row=rindex + <span class="number">1</span>, column=cindex, rowspan=<span class="number">2</span>, sticky=EW)</span><br><span class="line">                <span class="keyword">elif</span> c == <span class="number">0</span>:</span><br><span class="line">                    Button(self, text=c, width=<span class="number">2</span>)\</span><br><span class="line">                        .grid(row=rindex + <span class="number">1</span>, column=cindex, columnspan=<span class="number">2</span>, sticky=EW)</span><br><span class="line">                <span class="keyword">elif</span> c == <span class="string">&quot;.&quot;</span>:</span><br><span class="line">                    Button(self, text=c, width=<span class="number">2</span>)\</span><br><span class="line">                        .grid(row=rindex + <span class="number">1</span>, column=cindex+<span class="number">1</span>, sticky=EW)</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    Button(self, text=c, width=<span class="number">2</span>)\</span><br><span class="line">                        .grid(row=rindex+<span class="number">1</span>, column=cindex, sticky=EW)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;200x300+200+300&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113917.png" alt="image-20231208171458029"></p>
<h4 id="Pack布局管理器"><a href="#Pack布局管理器" class="headerlink" title="Pack布局管理器"></a>Pack布局管理器</h4><p>pack 按照组件的创建顺序将子组件添加到父组件中，按照垂直或者水平的方向自然排布。如果不指定任何选项，默认在父组件中自顶向下垂直添加组件。</p>
<p>pack 是代码量最少，最简单的一种，可以用于快速生成界面。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113918.png" alt="image-20231208171547373"></p>
<h4 id="钢琴软件界面设计"><a href="#钢琴软件界面设计" class="headerlink" title="钢琴软件界面设计"></a>钢琴软件界面设计</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 测试 pack 布局管理</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;700x220&quot;</span>)</span><br><span class="line"><span class="comment"># Frame 是一个矩形区域，就是用来防止其他子组件</span></span><br><span class="line">f1 = Frame(root)</span><br><span class="line">f1.pack()</span><br><span class="line">f2 = Frame(root)</span><br><span class="line">f2.pack()</span><br><span class="line">btnText = (<span class="string">&quot;流行风&quot;</span>, <span class="string">&quot;中国风&quot;</span>, <span class="string">&quot;日本风&quot;</span>, <span class="string">&quot;重金属&quot;</span>, <span class="string">&quot;轻音乐&quot;</span>)</span><br><span class="line"><span class="keyword">for</span> txt <span class="keyword">in</span> btnText:</span><br><span class="line">    Button(f1, text=txt).pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="number">20</span>):</span><br><span class="line">        Button(f2, width=<span class="number">5</span>, height=<span class="number">10</span>, bg=<span class="string">&quot;black&quot;</span> <span class="keyword">if</span> i % <span class="number">2</span> == <span class="number">0</span> <span class="keyword">else</span> <span class="string">&quot;white&quot;</span>).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113919.png" alt="image-20231208171932560"></p>
<h4 id="Place管理器"><a href="#Place管理器" class="headerlink" title="Place管理器"></a>Place管理器</h4><p>place 布局管理器可以通过坐标精确控制组件的位置，适用于一些布局更加灵活的场景。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113920.png" alt="image-20231208172220911"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;500x300&quot;</span>)</span><br><span class="line">root.title(<span class="string">&quot;布局管理 place&quot;</span>)</span><br><span class="line">root[<span class="string">&quot;bg&quot;</span>] = <span class="string">&quot;white&quot;</span></span><br><span class="line">f1 = Frame(root, width=<span class="number">200</span>, height=<span class="number">200</span>, bg=<span class="string">&quot;green&quot;</span>)</span><br><span class="line">f1.place(x=<span class="number">30</span>, y=<span class="number">30</span>) </span><br><span class="line">Button(root, text=<span class="string">&quot;尚学堂&quot;</span>).place(relx=<span class="number">0.5</span>, rely=<span class="number">0</span>,        <span class="comment"># 相对宽度和相对高度</span></span><br><span class="line">                               x=<span class="number">100</span>, y=<span class="number">200</span>, relwidth=<span class="number">0.2</span>, relheight=<span class="number">0.2</span>)  </span><br><span class="line">Button(f1, text=<span class="string">&quot;百战程序员&quot;</span>).place(relx=<span class="number">0.6</span>, rely=<span class="number">0.7</span>)</span><br><span class="line">Button(f1, text=<span class="string">&quot;高淇老师&quot;</span>).place(relx=<span class="number">0.2</span>, rely=<span class="number">0.2</span>)</span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113922.png" alt="image-20231208172552488"></p>
<h3 id="事件处理"><a href="#事件处理" class="headerlink" title="事件处理"></a>事件处理</h3><h4 id="扑克游戏界面设计-增加事件操作"><a href="#扑克游戏界面设计-增加事件操作" class="headerlink" title="扑克游戏界面设计-增加事件操作"></a>扑克游戏界面设计-增加事件操作</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;扑克牌游戏的界面设计&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super()代表的父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.place()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;通过place布局管理器实现扑克牌位置控制&quot;&quot;&quot;</span></span><br><span class="line">        <span class="comment"># 显示一张扑克</span></span><br><span class="line">        <span class="comment"># self.photo = PhotoImage(file=&quot;../images/puke/puke1.gif&quot;)</span></span><br><span class="line">        <span class="comment"># self.puke1 = Label(self.master, image=self.photo)</span></span><br><span class="line">        <span class="comment"># self.puke1.place(x=10, y=50)</span></span><br><span class="line">        <span class="comment"># 用列表推导式显示所有图片</span></span><br><span class="line">        self.photos = [PhotoImage(file=<span class="string">&quot;../images/puke/puke&quot;</span> + <span class="built_in">str</span>(i+<span class="number">1</span>) + <span class="string">&quot;.gif&quot;</span>) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>)]</span><br><span class="line">        self.pukes = [Label(self.master, image=self.photos[i]) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>)]</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">            self.pukes[i].place(x=<span class="number">10</span>+i*<span class="number">40</span>, y=<span class="number">50</span>)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 为所有Label增加事件处理</span></span><br><span class="line">        self.pukes[<span class="number">0</span>].bind_class(<span class="string">&quot;Label&quot;</span>, <span class="string">&quot;&lt;Button-1&gt;&quot;</span>, self.chupai)  <span class="comment"># 绑定左键</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">chupai</span>(<span class="params">self, event</span>):</span><br><span class="line">        <span class="built_in">print</span>(event.widget.winfo_geometry())</span><br><span class="line">        <span class="built_in">print</span>(event.widget.winfo_y())   <span class="comment"># 获得y坐标</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> event.widget.winfo_y() == <span class="number">50</span>:</span><br><span class="line">            event.widget.place(y=<span class="number">30</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            event.widget.place(y=<span class="number">50</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;600x300+200+300&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113923.png" alt="image-20231208191429645"></p>
<h4 id="lambda表达式-事件传参应用"><a href="#lambda表达式-事件传参应用" class="headerlink" title="lambda表达式-事件传参应用"></a>lambda表达式-事件传参应用</h4><p>lambda 表达式定义的是一个匿名函数，只适合简单输入参数，简单计算返回结果，不适合功能复杂情况。</p>
<p>lambda 定义的匿名函数也有输入、也有输出，只是没有名字。语法格式如下：</p>
<p>​                                                                    <code>lambda 参数值列表：表达式</code></p>
<p>参数值列表即为输入。</p>
<p>表达式计算的结构即为输出。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113924.png" alt="image-20231208192609616"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"><span class="comment"># 测试 command 属性绑定事件，测试 lambda 表达式帮助传参</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;270x50&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mouseTest1</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;command 方式，简单情况：不涉及获取 event 对象，可以使用&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mouseTest2</span>(<span class="params">a, b</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;a=&#123;0&#125;,b=&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(a, b))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Button(root, text=<span class="string">&quot;测试 command1&quot;</span>,</span><br><span class="line">       command=mouseTest1).pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line">Button(root, text=<span class="string">&quot;测试 command2&quot;</span>, </span><br><span class="line">       command=<span class="keyword">lambda</span>: mouseTest2(<span class="string">&quot;gaoqi&quot;</span>, <span class="string">&quot;xixi&quot;</span>)).pack(side=<span class="string">&quot;left&quot;</span>) <span class="comment"># lambda 表达式帮助传参</span></span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<h4 id="三种事件绑定方式总结"><a href="#三种事件绑定方式总结" class="headerlink" title="三种事件绑定方式总结"></a>三种事件绑定方式总结</h4><p><strong>多种事件绑定方式汇总</strong></p>
<p><strong>组件对象的绑定</strong></p>
<ol>
<li>通过 <code>command</code> 属性绑定（适合简单不需获取 event 对象）</li>
</ol>
<p><code>Button(root,text=&quot;登录&quot;,command=login)</code></p>
<ol>
<li>通过 <code>bind()</code>方法绑定（适合需要获取 event 对象）</li>
</ol>
<p><code>c1 = Canvas(); c1.bind(&quot;&lt;Button-1&gt;&quot;,drawLine)</code> </p>
<p><strong>组件类的绑定</strong></p>
<p>调用对象的 <code>bind_class</code> 函数，将该组件类所有的组件绑定事件：</p>
<p><code>w.bind_class(&quot;Widget&quot;,&quot;event&quot;,eventhanler)</code></p>
<p>比如：<code>btn01.bind_class(“Button”,&quot;&lt;Button-1&gt;&quot;,func)</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"><span class="comment"># 多种事件绑定方式汇总</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;270x30&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mouseTest1</span>(<span class="params">event</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;bind()方式绑定，可以获取 event 对象&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(event.widget)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mouseTest2</span>(<span class="params">a, b</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;a=&#123;0&#125;,b=&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(a, b))</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;command 方式绑定，不能直接获取 event 对象&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mouseTest3</span>(<span class="params">event</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;右键单击事件，绑定给所有按钮啦！！&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(event.widget)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">b1 = Button(root, text=<span class="string">&quot;测试 bind()绑定&quot;</span>)</span><br><span class="line">b1.pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line"><span class="comment"># bind 方式绑定事件</span></span><br><span class="line">b1.bind(<span class="string">&quot;&lt;Button-1&gt;&quot;</span>, mouseTest1)</span><br><span class="line"><span class="comment"># command 属性直接绑定事件</span></span><br><span class="line">b2 = Button(root, text=<span class="string">&quot;测试 command2&quot;</span>,</span><br><span class="line">            command=<span class="keyword">lambda</span>: mouseTest2(<span class="string">&quot;gaoqi&quot;</span>, <span class="string">&quot;xixi&quot;</span>))</span><br><span class="line">b2.pack(side=<span class="string">&quot;left&quot;</span>)</span><br><span class="line"><span class="comment"># 给所有 Button 按钮都绑定右键单击事件&lt;Button-2&gt;</span></span><br><span class="line">b1.bind_class(<span class="string">&quot;Button&quot;</span>, <span class="string">&quot;&lt;Button-2&gt;&quot;</span>, mouseTest3)</span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<h3 id="其他组件"><a href="#其他组件" class="headerlink" title="其他组件"></a>其他组件</h3><h4 id="optionmenu选项菜单"><a href="#optionmenu选项菜单" class="headerlink" title="optionmenu选项菜单"></a>optionmenu选项菜单</h4><p>OptionMenu（选择项）用来做多选一，选中的项在顶部显示。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;optionmenu 的使用测试&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;200x100&quot;</span>)</span><br><span class="line">v = StringVar(root)</span><br><span class="line">v.<span class="built_in">set</span>(<span class="string">&quot;百战程序员&quot;</span>)</span><br><span class="line">om = OptionMenu(root, v, <span class="string">&quot;尚学堂&quot;</span>, <span class="string">&quot;百战程序员&quot;</span>, <span class="string">&quot;卓越班[保底 18 万]&quot;</span>)</span><br><span class="line">om[<span class="string">&quot;width&quot;</span>] = <span class="number">10</span></span><br><span class="line">om.pack()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">test1</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;最喜爱的机构:&quot;</span>, v.get())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># v.set(&quot;尚学堂&quot;)    # 直接修改了 optionmenu 中选中的值</span></span><br><span class="line">Button(root, text=<span class="string">&quot;确定&quot;</span>, command=test1).pack()</span><br><span class="line">root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113925.png" alt="image-20231208195755098"></p>
<h4 id="scale滑块"><a href="#scale滑块" class="headerlink" title="scale滑块"></a>scale滑块</h4><p>Scale（移动滑块）用于在指定的数值区间，通过滑块的移动来选择值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot; Scale(移动滑块)的使用测试：使用Scale控制字体大小变化&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;400x150&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">test1</span>(<span class="params">value</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;滑块的值:&quot;</span>, value)</span><br><span class="line">    newFont = (<span class="string">&quot;宋体&quot;</span>, value)</span><br><span class="line">    a.config(font=newFont)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Scale(root, from_=<span class="number">10</span>, to=<span class="number">50</span>, length=<span class="number">200</span>, tickinterval=<span class="number">5</span>, orient=HORIZONTAL, command=test1)</span><br><span class="line">s1.pack()</span><br><span class="line">a = Label(root, text=<span class="string">&quot;百战程序员&quot;</span>, width=<span class="number">10</span>, height=<span class="number">1</span>, bg=<span class="string">&quot;black&quot;</span>, fg=<span class="string">&quot;white&quot;</span>)</span><br><span class="line">a.pack()</span><br><span class="line">root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113926.png" alt="image-20231208200121685"></p>
<h4 id="颜色框"><a href="#颜色框" class="headerlink" title="颜色框"></a>颜色框</h4><p>颜色选择框可以帮助我们设置背景色、前景色、画笔颜色、字体颜色等等。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;askcolor 颜色选择框的测试，改变背景色&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.colorchooser <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;400x150&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">test1</span>():</span><br><span class="line">    s1 = askcolor(color=<span class="string">&quot;red&quot;</span>, title=<span class="string">&quot;选择背景色&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(s1)</span><br><span class="line">    <span class="comment"># s1 的值是：((0.0, 0.0, 255.99609375), &#x27;#0000ff&#x27;)</span></span><br><span class="line">    root.config(bg=s1[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Button(root, text=<span class="string">&quot;选择背景色&quot;</span>, command=test1).pack()</span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113927.png" alt="image-20231208201753386"></p>
<h4 id="文件选择框"><a href="#文件选择框" class="headerlink" title="文件选择框"></a>文件选择框</h4><p>文件对话框帮助我们实现可视化的==操作目录、操作文件==。最后，将文件、目录的信息传入到程序中。文件对话框包含如下一些常用函数：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113928.png" alt="image-20231208203352425"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113929.png" alt="image-20231208203403744"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;文件对话框获取文件&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.filedialog <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk();</span><br><span class="line">root.geometry(<span class="string">&quot;400x100&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">test1</span>():</span><br><span class="line">    f = askopenfilename(title=<span class="string">&quot;上传文件&quot;</span>,</span><br><span class="line">                        initialdir=<span class="string">&quot;d:/&quot;</span>, filetypes=[(<span class="string">&quot;视频文件&quot;</span>, <span class="string">&quot;.mp4&quot;</span>)])</span><br><span class="line">    <span class="comment"># print(f)</span></span><br><span class="line">    show[<span class="string">&quot;text&quot;</span>] = f</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Button(root, text=<span class="string">&quot;选择编辑的视频文件&quot;</span>, command=test1).pack()</span><br><span class="line">show = Label(root, width=<span class="number">40</span>, height=<span class="number">3</span>, bg=<span class="string">&quot;green&quot;</span>)</span><br><span class="line">show.pack()</span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<h4 id="读取文件内容"><a href="#读取文件内容" class="headerlink" title="读取文件内容"></a>读取文件内容</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"><span class="comment"># askcolor 颜色选择框的测试，改变背景色</span></span><br><span class="line"><span class="comment"># 打开指定 txt 文件，并读出文件内容到窗口</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.filedialog <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;400x100&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">test1</span>():</span><br><span class="line">    <span class="keyword">with</span> askopenfile(title=<span class="string">&quot;上传文件&quot;</span>,</span><br><span class="line">                     initialdir=<span class="string">&quot;d:&quot;</span>, filetypes=[(<span class="string">&quot;文本文件&quot;</span>, <span class="string">&quot;.txt&quot;</span>)]) <span class="keyword">as</span> f:</span><br><span class="line">        show[<span class="string">&quot;text&quot;</span>] = f.read()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Button(root, text=<span class="string">&quot;选择读取的文本文件&quot;</span>, command=test1).pack()</span><br><span class="line">show = Label(root, width=<span class="number">40</span>, height=<span class="number">3</span>, bg=<span class="string">&quot;green&quot;</span>)</span><br><span class="line">show.pack()</span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<h4 id="简单对话框"><a href="#简单对话框" class="headerlink" title="简单对话框"></a>简单对话框</h4><p>simpledialog（简单对话框）包含如下常用函数：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113930.png" alt="image-20231208204359332"></p>
<p>参数中，title 表示窗口标题；</p>
<p>prompt 是提示信息；</p>
<p>命名参数 kw 为各种选项：initialvalue（初始值）、minvalue（最小值）、maxvalue（最大值）。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;简单对话框&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter.simpledialog <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;400x100&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">test1</span>():</span><br><span class="line">    a = askinteger(title=<span class="string">&quot;输入年龄&quot;</span>, prompt=<span class="string">&quot;请输入年龄&quot;</span>, initialvalue=<span class="number">18</span>, minvalue=<span class="number">1</span>, maxvalue=<span class="number">150</span>)</span><br><span class="line">    <span class="comment"># askstring、askfloat 框使用方式一样</span></span><br><span class="line">    show[<span class="string">&quot;text&quot;</span>] = a</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Button(root, text=<span class="string">&quot;你多大了? 请输入&quot;</span>, command=test1).pack()</span><br><span class="line">show = Label(root, width=<span class="number">40</span>, height=<span class="number">3</span>, bg=<span class="string">&quot;green&quot;</span>)</span><br><span class="line">show.pack()</span><br><span class="line">root.mainloop()</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113931.png" alt="image-20231208205056943"></p>
<h4 id="通用消息框"><a href="#通用消息框" class="headerlink" title="通用消息框"></a>通用消息框</h4><p>messagebox（通用消息框）用于和用户简单的交互，用户点击确定、取消。如下列出了</p>
<p>messagebox 的常见函数：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113932.png" alt="image-20231208204952327"><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312082113933.png" alt="image-20231208205010396"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;简单对话框&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.messagebox <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">root = Tk()</span><br><span class="line">root.geometry(<span class="string">&quot;400x100&quot;</span>)</span><br><span class="line">a1 = showinfo(title=<span class="string">&quot;尚学堂&quot;</span>, message=<span class="string">&quot;Python400 集从零开始，深入底层，\</span></span><br><span class="line"><span class="string">                                      深入算法，打好基础。还手写神经网络&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(a1)</span><br><span class="line">root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="ttk子模块问题"><a href="#ttk子模块问题" class="headerlink" title="ttk子模块问题"></a>ttk子模块问题</h4><p>我们再前面学的组件是 tkinter 模块下的组件，整体风格较老较丑。为了弥补这点不足，推出了 ttk 组件。ttk 组件更加美观、功能更加强大。 新增了 LabeledScale（带标签的Scale）、Notebook（多文档窗口）、Progressbar（进度条）、Treeview（树）等组件。</p>
<p>使用 ttk 组件与使用普通的 Tkinter 组件并没有多大的区别，只要导入 ttk 模块即可。</p>
<blockquote>
<p>:warning:此处我们不展开细讲 ttk。如果你的项目确实需要用到复杂的界面，推荐大家使用<code>wxpython</code> 或者 <code>pyQt</code>.</p>
</blockquote>
<h3 id="菜单"><a href="#菜单" class="headerlink" title="菜单"></a>菜单</h3><h4 id="主菜单"><a href="#主菜单" class="headerlink" title="主菜单"></a>主菜单</h4><p>主菜单一般包含：文件、编辑、帮助等，位于 GUI 窗口的上面。创建主菜单一般有如下 4步：</p>
<ol>
<li>创建主菜单栏对象</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">menubar = tk.Menu(root)</span><br></pre></td></tr></table></figure>
<ol>
<li>创建菜单，并添加到主菜单栏对象</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">file_menu = tk.Menu(menubar)</span><br><span class="line">menubar.add_cascade(label=<span class="string">&quot;文件&quot;</span>,menu=file_menu)</span><br></pre></td></tr></table></figure>
<ol>
<li>添加菜单项到 2 步中的菜单</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">file_menu.add_command(label=<span class="string">&quot;打开&quot;</span>)</span><br><span class="line">file_menu.add_command(label=<span class="string">&quot;保存&quot;</span>,accelerator=<span class="string">&quot;ctrl + s&quot;</span> command=mySaveFile)</span><br><span class="line">file_menu.add_separator()</span><br><span class="line">file_menu.add_command(label=<span class="string">&quot;退出&quot;</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>将主菜单栏添加到根窗口</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">root[<span class="string">&quot;menu&quot;</span>]=menubar</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;开发记事本软件的菜单&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.filedialog <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.colorchooser <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)    <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.textpad = <span class="literal">None</span>         <span class="comment"># textpad 表示 Text 文本框对象</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 创建主菜单栏</span></span><br><span class="line">        menubar = Menu(root)</span><br><span class="line">        <span class="comment"># 创建子菜单</span></span><br><span class="line">        menuFile = Menu(menubar)</span><br><span class="line">        menuEdit = Menu(menubar)</span><br><span class="line">        menuHelp = Menu(menubar)</span><br><span class="line">        <span class="comment"># 将子菜单加入到主菜单栏</span></span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;文件(F)&quot;</span>, menu=menuFile)</span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;编辑(E)&quot;</span>, menu=menuEdit)</span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;帮助(H)&quot;</span>, menu=menuHelp)</span><br><span class="line">        <span class="comment"># 添加菜单项</span></span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;新建&quot;</span>, accelerator=<span class="string">&quot;ctrl+n&quot;</span>,</span><br><span class="line">                             command=self.test)</span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;打开&quot;</span>, accelerator=<span class="string">&quot;ctrl+o&quot;</span>,</span><br><span class="line">                             command=self.test)</span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;保存&quot;</span>,</span><br><span class="line">                             accelerator=<span class="string">&quot;ctrl+s&quot;</span>, command=self.test)</span><br><span class="line">        menuFile.add_separator()  <span class="comment"># 添加分割线</span></span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;退出&quot;</span>,</span><br><span class="line">                             accelerator=<span class="string">&quot;ctrl+q&quot;</span>, command=self.test)</span><br><span class="line">        <span class="comment"># 将主菜单栏加到根窗口</span></span><br><span class="line">        root[<span class="string">&quot;menu&quot;</span>] = menubar</span><br><span class="line">        <span class="comment"># 文本编辑区</span></span><br><span class="line">        self.textpad = Text(root, width=<span class="number">50</span>, height=<span class="number">30</span>)</span><br><span class="line">        self.textpad.pack()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">test</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;450x300+200+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;简易记事本&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<h4 id="上下文菜单"><a href="#上下文菜单" class="headerlink" title="上下文菜单"></a>上下文菜单</h4><p>快捷菜单（上下文菜单）是通过鼠标右键单击组件而弹出的菜单，一般是和这个组件相关的操作，比如：剪切、复制、粘贴、属性等。创建快捷菜单步骤如下：</p>
<ol>
<li>创建菜单</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">menubar = tk.Menu(root)</span><br><span class="line">menubar.add_command(label=<span class="string">&quot;字体&quot;</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>绑定鼠标右键单击事件</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">test</span>(<span class="params">event</span>):</span><br><span class="line">    menubar.post(event.x_root,event.y_root)  <span class="comment">#在鼠标右键单击坐标处显示菜单</span></span><br><span class="line">    root.bind(<span class="string">&quot;&lt;Button-3&gt;&quot;</span>,test)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;开发记事本软件的菜单&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.filedialog <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.colorchooser <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)    <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.textpad = <span class="literal">None</span>         <span class="comment"># textpad 表示 Text 文本框对象</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 创建主菜单栏</span></span><br><span class="line">        menubar = Menu(root)</span><br><span class="line">        <span class="comment"># 创建子菜单</span></span><br><span class="line">        menuFile = Menu(menubar)</span><br><span class="line">        menuEdit = Menu(menubar)</span><br><span class="line">        menuHelp = Menu(menubar)</span><br><span class="line">        <span class="comment"># 将子菜单加入到主菜单栏</span></span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;文件(F)&quot;</span>, menu=menuFile)</span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;编辑(E)&quot;</span>, menu=menuEdit)</span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;帮助(H)&quot;</span>, menu=menuHelp)</span><br><span class="line">        <span class="comment"># 添加菜单项</span></span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;新建&quot;</span>, accelerator=<span class="string">&quot;ctrl+n&quot;</span>,</span><br><span class="line">                             command=self.test)</span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;打开&quot;</span>, accelerator=<span class="string">&quot;ctrl+o&quot;</span>,</span><br><span class="line">                             command=self.test)</span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;保存&quot;</span>,</span><br><span class="line">                             accelerator=<span class="string">&quot;ctrl+s&quot;</span>, command=self.test)</span><br><span class="line">        menuFile.add_separator()  <span class="comment"># 添加分割线</span></span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;退出&quot;</span>,</span><br><span class="line">                             accelerator=<span class="string">&quot;ctrl+q&quot;</span>, command=self.test)</span><br><span class="line">        <span class="comment"># 将主菜单栏加到根窗口</span></span><br><span class="line">        root[<span class="string">&quot;menu&quot;</span>] = menubar</span><br><span class="line">        <span class="comment"># 文本编辑区</span></span><br><span class="line">        self.textpad = Text(root, width=<span class="number">50</span>, height=<span class="number">30</span>)</span><br><span class="line">        self.textpad.pack()</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 创建上下文菜单</span></span><br><span class="line">        self.contextMenu = Menu(root)</span><br><span class="line">        self.contextMenu.add_command(label=<span class="string">&quot;背景颜色&quot;</span>,  command=self.test)</span><br><span class="line">        <span class="comment"># 为右键绑定事件</span></span><br><span class="line">        root.bind(<span class="string">&quot;&lt;Button-3&gt;&quot;</span>, self.createContextMenu)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">test</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createContextMenu</span>(<span class="params">self, event</span>):</span><br><span class="line">        <span class="comment"># 菜单在鼠标右键单击的坐标显示</span></span><br><span class="line">        self.contextMenu.post(event.x_root, event.y_root)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;450x300+200+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;简易记事本&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312122142441.png" alt="image-20231209170627199"></p>
<h3 id="记事本项目"><a href="#记事本项目" class="headerlink" title="记事本项目"></a>记事本项目</h3><p>结合所学 GUI 知识，开发一款模仿 windows 记事本的软件。包含了基本的功能：</p>
<ol>
<li><p>新建文本文件</p>
</li>
<li><p>保存文件</p>
</li>
<li><p>修改文件内容</p>
</li>
<li><p>退出</p>
</li>
<li><p>各种快捷键处理</p>
</li>
<li><p>修改文本区域背景色</p>
</li>
</ol>
<h4 id="【01】打开和保存修改文件的实现"><a href="#【01】打开和保存修改文件的实现" class="headerlink" title="【01】打开和保存修改文件的实现"></a>【01】打开和保存修改文件的实现</h4><h4 id="【02】新建文件-背景色改变-快捷键功能"><a href="#【02】新建文件-背景色改变-快捷键功能" class="headerlink" title="【02】新建文件-背景色改变-快捷键功能"></a>【02】新建文件-背景色改变-快捷键功能</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">开发一个简单的记事本。</span></span><br><span class="line"><span class="string">包含：新建、保存、修改文本内容、退出</span></span><br><span class="line"><span class="string">包含：各种快捷键的处理</span></span><br><span class="line"><span class="string">version 1.0</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.filedialog <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.colorchooser <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.textpad = <span class="literal">None</span>  <span class="comment"># textpad 表示 Text 文本框对象</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 创建主菜单栏</span></span><br><span class="line">        menubar = Menu(root)</span><br><span class="line">        <span class="comment"># 创建子菜单</span></span><br><span class="line">        menuFile = Menu(menubar)</span><br><span class="line">        menuEdit = Menu(menubar)</span><br><span class="line">        menuHelp = Menu(menubar)</span><br><span class="line">        <span class="comment"># 将子菜单加入到主菜单栏</span></span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;文件(F)&quot;</span>, menu=menuFile)</span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;编辑(E)&quot;</span>, menu=menuEdit)</span><br><span class="line">        menubar.add_cascade(label=<span class="string">&quot;帮助(H)&quot;</span>, menu=menuHelp)</span><br><span class="line">        <span class="comment"># 添加菜单项</span></span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;新建&quot;</span>, accelerator=<span class="string">&quot;ctrl+n&quot;</span>,</span><br><span class="line">                             command=self.newfile)</span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;打开&quot;</span>, accelerator=<span class="string">&quot;ctrl+o&quot;</span>,</span><br><span class="line">                             command=self.openfile)</span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;保存&quot;</span>,</span><br><span class="line">                             accelerator=<span class="string">&quot;ctrl+s&quot;</span>, command=self.savefile)</span><br><span class="line">        menuFile.add_separator()  <span class="comment"># 添加分割线</span></span><br><span class="line">        menuFile.add_command(label=<span class="string">&quot;退出&quot;</span>,</span><br><span class="line">                             accelerator=<span class="string">&quot;ctrl+q&quot;</span>, command=self.exit)</span><br><span class="line">        <span class="comment"># 将主菜单栏加到根窗口</span></span><br><span class="line">        root[<span class="string">&quot;menu&quot;</span>] = menubar</span><br><span class="line">        <span class="comment"># 增加快捷键的处理</span></span><br><span class="line">        root.bind(<span class="string">&quot;&lt;Control-n&gt;&quot;</span>, <span class="keyword">lambda</span> event: self.newfile())   <span class="comment"># 新建文件快捷键</span></span><br><span class="line">        root.bind(<span class="string">&quot;&lt;Control-o&gt;&quot;</span>, <span class="keyword">lambda</span> event: self.openfile())  <span class="comment"># 打开新文件快捷键</span></span><br><span class="line">        root.bind(<span class="string">&quot;&lt;Control-s&gt;&quot;</span>, <span class="keyword">lambda</span> event: self.savefile())  <span class="comment"># 保存文件快捷键</span></span><br><span class="line">        root.bind(<span class="string">&quot;&lt;Control-q&gt;&quot;</span>, <span class="keyword">lambda</span> event: self.exit())      <span class="comment"># 退出快捷键</span></span><br><span class="line">        <span class="comment"># 文本编辑区</span></span><br><span class="line">        self.textpad = Text(root, width=<span class="number">50</span>, height=<span class="number">30</span>)</span><br><span class="line">        self.textpad.pack()</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 创建上下文菜单</span></span><br><span class="line">        self.contextMenu = Menu(root)</span><br><span class="line">        self.contextMenu.add_command(label=<span class="string">&quot;背景颜色&quot;</span>, command=self.openAskColor)</span><br><span class="line">        <span class="comment"># 为右键绑定事件</span></span><br><span class="line">        root.bind(<span class="string">&quot;&lt;Button-3&gt;&quot;</span>, self.createContextMenu)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">newfile</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 每次打开文件之前清空text控件之前的内容</span></span><br><span class="line">        self.textpad.delete(<span class="number">1.0</span>, END)</span><br><span class="line">        self.filename = asksaveasfilename(title=<span class="string">&quot;另存为&quot;</span>, initialfile=<span class="string">&quot;未命名.txt&quot;</span>,</span><br><span class="line">                                          filetypes=[(<span class="string">&quot;文本文档&quot;</span>, <span class="string">&quot;*.txt&quot;</span>)],</span><br><span class="line">                                          defaultextension=<span class="string">&quot;.txt&quot;</span>)</span><br><span class="line">        self.savefile()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">openfile</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 每次打开文件之前清空text控件之前的内容</span></span><br><span class="line">        self.textpad.delete(<span class="number">1.0</span>, END)</span><br><span class="line">        <span class="keyword">with</span> askopenfile(title=<span class="string">&quot;打开文本文件&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">            self.textpad.insert(INSERT, f.read())</span><br><span class="line">            self.filename = f.name</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">savefile</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">with</span> <span class="built_in">open</span>(self.filename, <span class="string">&quot;w&quot;</span>) <span class="keyword">as</span> f:</span><br><span class="line">            c = self.textpad.get(<span class="number">1.0</span>, END)</span><br><span class="line">            f.write(c)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">exit</span>(<span class="params">self</span>):</span><br><span class="line">        root.quit()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">openAskColor</span>(<span class="params">self</span>):</span><br><span class="line">        color = askcolor(color=<span class="string">&quot;red&quot;</span>, title=<span class="string">&quot;选择背景颜色&quot;</span>)</span><br><span class="line">        <span class="comment"># 返回格式 ((0,0,0,255),&quot;0000ff&quot;)</span></span><br><span class="line">        self.textpad.config(bg=color[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createContextMenu</span>(<span class="params">self, event</span>):</span><br><span class="line">        <span class="comment"># 菜单在鼠标右键单击的坐标显示</span></span><br><span class="line">        self.contextMenu.post(event.x_root, event.y_root)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="string">&quot;450x300+200+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;简易记事本&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<h4 id="【03】python项目打包成exe可执行文件"><a href="#【03】python项目打包成exe可执行文件" class="headerlink" title="【03】python项目打包成exe可执行文件"></a>【03】python项目打包成exe可执行文件</h4><p>我们可以使用 pyinstaller 模块实现将 python 项目打包成 exe 文件。操作步骤如下：</p>
<ol>
<li><p>安装 pyinstaller 模块</p>
<p>在 pycharm 中操作：file—&gt;setting—&gt;Project：xxx —&gt;Project interpretor，再点击+即可。</p>
</li>
<li><p>在 pycharm 的 Terminal 终端输入如下命令：</p>
<p><code>pyinstaller  -F  xxxx.py</code></p>
<blockquote>
<p>:warning:相关参数如下：</p>
<p>—icon= 图标路径（<code>pyinstaller -F --icon=my.ico XXXX.py</code>）</p>
<p>-F 打包成一个 exe 文件</p>
<p>-w 使用窗口，无控制台</p>
<p>-c 使用控制台，无窗口</p>
<p>-D 创建一个目录，里面包含 exe 以及其他一些依赖性文件</p>
</blockquote>
</li>
<li><p>在项目的 dist 目录下可以看到生成了 exe 文件，直接在 windows 系统中使用即可</p>
</li>
</ol>
<blockquote>
<p>:warning:==exe 文件本质是将 python 解释器和程序打包到了一起，这样我们执行程序时就不用管 windows 系统是不是有 python 解释器。==</p>
</blockquote>
<h3 id="画图项目"><a href="#画图项目" class="headerlink" title="画图项目"></a>画图项目</h3><p>开发一款简单的画图软件, 包含如下功能：</p>
<ol>
<li><p>画笔</p>
</li>
<li><p>矩形/椭圆绘制</p>
</li>
<li><p>清屏</p>
</li>
<li><p>橡皮擦</p>
</li>
<li><p>直线/带箭头的直线</p>
</li>
<li><p>修改画笔颜色、背景颜色</p>
</li>
</ol>
<h4 id="【01】界面实现"><a href="#【01】界面实现" class="headerlink" title="【01】界面实现"></a>【01】界面实现</h4><h4 id="【02】绘制直线-拖动删除上一个图形"><a href="#【02】绘制直线-拖动删除上一个图形" class="headerlink" title="【02】绘制直线-拖动删除上一个图形"></a>【02】绘制直线-拖动删除上一个图形</h4><h4 id="【03】箭头直线-矩形绘制"><a href="#【03】箭头直线-矩形绘制" class="headerlink" title="【03】箭头直线-矩形绘制"></a>【03】箭头直线-矩形绘制</h4><h4 id="【04】画笔和橡皮擦实现"><a href="#【04】画笔和橡皮擦实现" class="headerlink" title="【04】画笔和橡皮擦实现"></a>【04】画笔和橡皮擦实现</h4><h4 id="【05】清屏-颜色框-快捷键处理"><a href="#【05】清屏-颜色框-快捷键处理" class="headerlink" title="【05】清屏-颜色框-快捷键处理"></a>【05】清屏-颜色框-快捷键处理</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">开发画图软件的菜单</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> tkinter <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.filedialog <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">from</span> tkinter.colorchooser <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"><span class="comment"># 　窗口的高度和宽度</span></span><br><span class="line">win_heigth = <span class="number">450</span></span><br><span class="line">win_width = <span class="number">900</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span>(<span class="title class_ inherited__">Frame</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, master=<span class="literal">None</span>, bgcolor=<span class="string">&quot;#000000&quot;</span></span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(master)  <span class="comment"># super()代表的是父类的定义，而不是父类对象</span></span><br><span class="line">        self.master = master</span><br><span class="line">        self.bgcolor = bgcolor</span><br><span class="line">        self.x = <span class="number">0</span></span><br><span class="line">        self.y = <span class="number">0</span></span><br><span class="line">        self.fgcolor = <span class="string">&quot;#ff0000&quot;</span></span><br><span class="line">        <span class="comment"># 表示最后绘制图像的id</span></span><br><span class="line">        self.lastDraw = <span class="number">0</span></span><br><span class="line">        <span class="comment"># 最初的绘画标记</span></span><br><span class="line">        self.startDrawFlag = <span class="literal">False</span></span><br><span class="line">        self.pack()</span><br><span class="line">        self.createWidget()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWidget</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 创建绘图区</span></span><br><span class="line">        self.drawpad = Canvas(root, width=win_width, height=win_heigth * <span class="number">0.9</span>, bg=self.bgcolor)</span><br><span class="line">        self.drawpad.pack()</span><br><span class="line">        <span class="comment"># 创建按钮</span></span><br><span class="line">        btn_start = Button(root, text=<span class="string">&quot;开始&quot;</span>, name=<span class="string">&quot;start&quot;</span>)</span><br><span class="line">        btn_start.pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line">        btn_pen = Button(root, text=<span class="string">&quot;画笔&quot;</span>, name=<span class="string">&quot;pen&quot;</span>)</span><br><span class="line">        btn_pen.pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line">        btn_rect = Button(root, text=<span class="string">&quot;矩形&quot;</span>, name=<span class="string">&quot;rect&quot;</span>)</span><br><span class="line">        btn_rect.pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line">        btn_clear = Button(root, text=<span class="string">&quot;清屏&quot;</span>, name=<span class="string">&quot;clear&quot;</span>)</span><br><span class="line">        btn_clear.pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line">        btn_eraser = Button(root, text=<span class="string">&quot;橡皮擦&quot;</span>, name=<span class="string">&quot;eraser&quot;</span>)</span><br><span class="line">        btn_eraser.pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line">        btn_lineArrow = Button(root, text=<span class="string">&quot;箭头直线&quot;</span>, name=<span class="string">&quot;lineArrow&quot;</span>)</span><br><span class="line">        btn_lineArrow.pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line">        btn_color = Button(root, text=<span class="string">&quot;颜色&quot;</span>, name=<span class="string">&quot;color&quot;</span>)</span><br><span class="line">        btn_color.pack(side=<span class="string">&quot;left&quot;</span>, padx=<span class="string">&quot;10&quot;</span>)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 事件处理</span></span><br><span class="line">        btn_pen.bind_class(<span class="string">&quot;Button&quot;</span>, <span class="string">&quot;&lt;1&gt;&quot;</span>, self.event_Manager)</span><br><span class="line">        self.drawpad.bind(<span class="string">&quot;ButtonRelease-1&quot;</span>, self.stopDraw)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 增加颜色切换的快捷键</span></span><br><span class="line">        root.bind(<span class="string">&quot;&lt;KeyPress-r&gt;&quot;</span>,self.kuaijiejian)</span><br><span class="line">        root.bind(<span class="string">&quot;&lt;KeyPress-g&gt;&quot;</span>,self.kuaijiejian)</span><br><span class="line">        root.bind(<span class="string">&quot;&lt;KeyPress-y&gt;&quot;</span>,self.kuaijiejian)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">event_Manager</span>(<span class="params">self, event</span>):</span><br><span class="line">        name = event.widget.winfo_name()</span><br><span class="line">        <span class="built_in">print</span>(name)</span><br><span class="line">        <span class="keyword">if</span> name == <span class="string">&quot;line&quot;</span>:</span><br><span class="line">            <span class="comment"># 绑定拖动鼠标</span></span><br><span class="line">            self.drawpad.bind(<span class="string">&quot;&lt;B1-Motion&gt;&quot;</span>, self.myLine)</span><br><span class="line">        <span class="keyword">elif</span> name == <span class="string">&quot;lineArrow&quot;</span>:</span><br><span class="line">            self.drawpad.bind(<span class="string">&quot;&lt;B1-Motion&gt;&quot;</span>, self.myLineArrow)</span><br><span class="line">        <span class="keyword">elif</span> name == <span class="string">&quot;rect&quot;</span>:</span><br><span class="line">            self.drawpad.bind(<span class="string">&quot;&lt;B1-Motion&gt;&quot;</span>, self.myRect)</span><br><span class="line">        <span class="keyword">elif</span> name == <span class="string">&quot;pen&quot;</span>:</span><br><span class="line">            self.drawpad.bind(<span class="string">&quot;&lt;B1-Motion&gt;&quot;</span>, self.myPen)</span><br><span class="line">        <span class="keyword">elif</span> name == <span class="string">&quot;eraser&quot;</span>:</span><br><span class="line">            self.drawpad.bind(<span class="string">&quot;&lt;B1-Motion&gt;&quot;</span>, self.myEraser)</span><br><span class="line">        <span class="keyword">elif</span> name == <span class="string">&quot;clear&quot;</span>:</span><br><span class="line">            self.drawpad.delete(<span class="string">&quot;all&quot;</span>)</span><br><span class="line">        <span class="keyword">elif</span> name == <span class="string">&quot;color&quot;</span>:</span><br><span class="line">            c = askcolor(color=self.fgcolor, title=<span class="string">&quot;选择画笔颜色&quot;</span>)</span><br><span class="line">            <span class="comment"># [(255,0,0),&quot;#ff0000&quot;]</span></span><br><span class="line">            self.fgcolor = c[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stopDraw</span>(<span class="params">self, event</span>):</span><br><span class="line">        self.startDrawFlag = <span class="literal">False</span></span><br><span class="line">        self.lastDraw = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">startDraw</span>(<span class="params">self, event</span>):</span><br><span class="line">        self.drawpad.delete(self.lastDraw)</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.startDrawFlag:</span><br><span class="line">            self.startDrawFlag = <span class="literal">True</span></span><br><span class="line">            self.x = event.x</span><br><span class="line">            self.y = event.y</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myLine</span>(<span class="params">self, event</span>):</span><br><span class="line">        self.startDraw(event)</span><br><span class="line">        self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myLineArrow</span>(<span class="params">self, event</span>):</span><br><span class="line">        self.startDraw(event)</span><br><span class="line">        self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, arrow=LAST, fill=self.fgcolor)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myRect</span>(<span class="params">self, event</span>):</span><br><span class="line">        self.startDraw(event)</span><br><span class="line">        self.lastDraw = self.drawpad.create_rectangle(self.x, self.y, event.x, event.y, outline=self.fgcolor)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myPen</span>(<span class="params">self, event</span>):</span><br><span class="line">        self.startDraw(event)</span><br><span class="line">        self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)</span><br><span class="line">        self.x = event.x</span><br><span class="line">        self.y = event.y</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myEraser</span>(<span class="params">self, event</span>):</span><br><span class="line">        self.startDraw(event)</span><br><span class="line">        self.drawpad.create_rectangle(event.x - <span class="number">4</span>, event.y - <span class="number">4</span>, event.x + <span class="number">4</span>, event.y + <span class="number">4</span>, fill=self.bgcolor)</span><br><span class="line">        self.x = event.x</span><br><span class="line">        self.y = event.y</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">kuaijiejian</span>(<span class="params">self, event</span>):</span><br><span class="line">        <span class="keyword">if</span> event.char == <span class="string">&quot;r&quot;</span>:</span><br><span class="line">            self.fgcolor = <span class="string">&quot;#ff0000&quot;</span></span><br><span class="line">        <span class="keyword">if</span> event.char == <span class="string">&quot;g&quot;</span>:</span><br><span class="line">            self.fgcolor = <span class="string">&quot;#00ff00&quot;</span></span><br><span class="line">        <span class="keyword">if</span> event.char == <span class="string">&quot;y&quot;</span>:</span><br><span class="line">            self.fgcolor = <span class="string">&quot;#ffff00&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    root = Tk()</span><br><span class="line">    root.geometry(<span class="built_in">str</span>(win_width) + <span class="string">&quot;x&quot;</span> + <span class="built_in">str</span>(win_heigth) + <span class="string">&quot;+200+300&quot;</span>)</span><br><span class="line">    root.title(<span class="string">&quot;画图软件&quot;</span>)</span><br><span class="line">    app = Application(master=root)</span><br><span class="line">    root.mainloop()</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202312122142443.png" alt="image-20231212214159088"></p>
<h2 id="游戏开发-坦克大战"><a href="#游戏开发-坦克大战" class="headerlink" title="游戏开发-坦克大战"></a>游戏开发-坦克大战</h2><h3 id="pygame模块的安装"><a href="#pygame模块的安装" class="headerlink" title="pygame模块的安装"></a>pygame模块的安装</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install pygame</span><br></pre></td></tr></table></figure>
<h3 id="面向对象分析项目需求"><a href="#面向对象分析项目需求" class="headerlink" title="面向对象分析项目需求"></a>面向对象分析项目需求</h3><p>坦克大战游戏的需求</p>
<p>1.顶目中有哪些类</p>
<p>2.每个类中有哪些方法</p>
<p>（1）坦克类（我方坦克、敌方坦克）</p>
<p>​            射击<br>​                    移动类<br>​                    显示坦克的方法</p>
<p>（2）子弹类</p>
<p>​            移动<br>​                    显示子弹的方法</p>
<p>（3）墙壁类</p>
<p>​            属性：是否可以通过</p>
<p>（4）爆炸效果类</p>
<p>​            展示爆炸效果</p>
<p>（5）音效类</p>
<p>​            播放音乐</p>
<p>（6）主类</p>
<p>​            开始游戏</p>
<p>​            结束游戏</p>
<h3 id="坦克大战项目框架搭建"><a href="#坦克大战项目框架搭建" class="headerlink" title="坦克大战项目框架搭建"></a>坦克大战项目框架搭建</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MainGame</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">startGame</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">endGame</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Tank</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 移动</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">move</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 射击</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">shot</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 展示坦克的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayTank</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 我方坦克</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyTank</span>(<span class="title class_ inherited__">Tank</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 敌方坦克</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">EnemyTank</span>(<span class="title class_ inherited__">Tank</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 子弹类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Bullet</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 移动</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">move</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 展示子弹的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayBullet</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span> </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 墙壁类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Wall</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 展示墙壁的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayWall</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 爆炸类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Expode</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 展示爆炸效果的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayExpode</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 音效类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Music</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 播放音乐的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">play</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<h3 id="加载主窗口"><a href="#加载主窗口" class="headerlink" title="加载主窗口"></a>加载主窗口</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    加载主窗口</span><br><span class="line">    pygame官方网址：www.pygame.org</span><br></pre></td></tr></table></figure>
<h3 id="坦克大战之事件处理"><a href="#坦克大战之事件处理" class="headerlink" title="坦克大战之事件处理"></a>坦克大战之事件处理</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    添加事件</span><br><span class="line">    1.点击关闭 关闭窗口</span><br><span class="line">    2.按下键盘时候，判断键盘按下的是什么键，分别对不同的键做处理</span><br></pre></td></tr></table></figure>
<h3 id="左上角文字的绘制"><a href="#左上角文字的绘制" class="headerlink" title="左上角文字的绘制"></a>左上角文字的绘制</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    左上角文字绘制：</span><br><span class="line">    左上角输出敌方坦克的数量6</span><br></pre></td></tr></table></figure>
<h3 id="加载我方坦克"><a href="#加载我方坦克" class="headerlink" title="加载我方坦克"></a>加载我方坦克</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    加载我方坦克</span><br></pre></td></tr></table></figure>
<h3 id="我方坦克切换方向移动"><a href="#我方坦克切换方向移动" class="headerlink" title="我方坦克切换方向移动"></a>我方坦克切换方向移动</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    1.我方坦克切换方向</span><br><span class="line">    2.我方坦克移动</span><br></pre></td></tr></table></figure>
<h3 id="我方坦克移动优化"><a href="#我方坦克移动优化" class="headerlink" title="我方坦克移动优化"></a>我方坦克移动优化</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    优化我方坦克移动的方法</span><br></pre></td></tr></table></figure>
<h3 id="我方坦克优化2"><a href="#我方坦克优化2" class="headerlink" title="我方坦克优化2"></a>我方坦克优化2</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    优化:按下方向键，坦克一直移动</span><br><span class="line">         松开方向键，坦克停止</span><br></pre></td></tr></table></figure>
<h3 id="加载敌方坦克"><a href="#加载敌方坦克" class="headerlink" title="加载敌方坦克"></a>加载敌方坦克</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    1.完善敌方坦克初始化方法</span><br><span class="line">    2.创建敌方坦克并展示</span><br></pre></td></tr></table></figure>
<h3 id="敌方坦克随机移动"><a href="#敌方坦克随机移动" class="headerlink" title="敌方坦克随机移动"></a>敌方坦克随机移动</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    1.优化左上角 文字的显示，将敌方坦克的数量进行修改</span><br><span class="line">    2.敌方坦克随机移动</span><br><span class="line">      思路：新增加一个变量步数，当移动时候步数进行递减</span><br><span class="line">            当步数&lt;=0时候修改敌方坦克的方向,并将步数复位</span><br></pre></td></tr></table></figure>
<h3 id="完善子弹类"><a href="#完善子弹类" class="headerlink" title="完善子弹类"></a>完善子弹类</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     完善子弹类</span><br></pre></td></tr></table></figure>
<h3 id="我方坦克发射子弹"><a href="#我方坦克发射子弹" class="headerlink" title="我方坦克发射子弹"></a>我方坦克发射子弹</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     完成我方坦克发射子弹</span><br></pre></td></tr></table></figure>
<h3 id="子弹移动"><a href="#子弹移动" class="headerlink" title="子弹移动"></a>子弹移动</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     完成我方坦克发射子弹,并完成子弹的移动</span><br></pre></td></tr></table></figure>
<h3 id="子弹消亡及数量控制"><a href="#子弹消亡及数量控制" class="headerlink" title="子弹消亡及数量控制"></a>子弹消亡及数量控制</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     优化：1.如果子弹碰到墙壁，让子弹消失</span><br><span class="line">           2.最多可以发射3颗子弹，不能一直发射</span><br></pre></td></tr></table></figure>
<h3 id="敌方坦克发射子弹"><a href="#敌方坦克发射子弹" class="headerlink" title="敌方坦克发射子弹"></a>敌方坦克发射子弹</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     优化：1.如果子弹碰到墙壁，让子弹消失</span><br><span class="line">           2.最多可以发射3颗子弹，不能一直发射</span><br></pre></td></tr></table></figure>
<h3 id="我方子弹与敌方坦克的碰撞"><a href="#我方子弹与敌方坦克的碰撞" class="headerlink" title="我方子弹与敌方坦克的碰撞"></a>我方子弹与敌方坦克的碰撞</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     我方子弹与敌方坦克的碰撞</span><br><span class="line">       精灵类 Sprite类</span><br></pre></td></tr></table></figure>
<h3 id="实现爆炸效果"><a href="#实现爆炸效果" class="headerlink" title="实现爆炸效果"></a>实现爆炸效果</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     1.完善爆炸效果类</span><br><span class="line">     2.在窗口中展示爆炸效果</span><br></pre></td></tr></table></figure>
<h3 id="我方坦克的消亡"><a href="#我方坦克的消亡" class="headerlink" title="我方坦克的消亡"></a>我方坦克的消亡</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     1.敌方子弹与我方坦克的碰撞</span><br><span class="line">     2.添加爆炸效果</span><br></pre></td></tr></table></figure>
<h3 id="我方坦克无限重生"><a href="#我方坦克无限重生" class="headerlink" title="我方坦克无限重生"></a>我方坦克无限重生</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">    让我方坦克无限重生</span><br><span class="line">      1.按下键盘的Esc让重生</span><br><span class="line">      2.重生及重新创建我方坦克</span><br></pre></td></tr></table></figure>
<h3 id="加载墙壁"><a href="#加载墙壁" class="headerlink" title="加载墙壁"></a>加载墙壁</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     添加墙壁</span><br><span class="line">     1.完善墙壁类，初始化方法</span><br><span class="line">     2.初始化墙壁，并将墙壁存储到列表中，在窗口中加载墙壁</span><br></pre></td></tr></table></figure>
<h3 id="子弹不穿墙"><a href="#子弹不穿墙" class="headerlink" title="子弹不穿墙"></a>子弹不穿墙</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     1.子弹不能穿墙</span><br><span class="line">        子弹碰撞到墙壁时候，让子弹消失</span><br><span class="line">     2.墙壁被击中，墙壁的生命值处理</span><br></pre></td></tr></table></figure>
<h3 id="坦克不能穿墙"><a href="#坦克不能穿墙" class="headerlink" title="坦克不能穿墙"></a>坦克不能穿墙</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     1.坦克不能穿墙</span><br><span class="line">        坦克碰撞到墙壁，不能再移动</span><br><span class="line">        不能再移动及坐标不能发生变化</span><br></pre></td></tr></table></figure>
<h3 id="敌我双方坦克发生碰撞"><a href="#敌我双方坦克发生碰撞" class="headerlink" title="敌我双方坦克发生碰撞"></a>敌我双方坦克发生碰撞</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     1.我方坦克与敌方坦克发生碰撞</span><br><span class="line">       让我方坦克不能再继续移动   stay()</span><br><span class="line">     2.敌方坦克与我方坦克发生碰撞</span><br><span class="line">       让地方坦克不能再移动   stay()</span><br></pre></td></tr></table></figure>
<h3 id="音效处理"><a href="#音效处理" class="headerlink" title="音效处理"></a>音效处理</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">新增功能：</span><br><span class="line">     1.完善音效类</span><br><span class="line">     2.添加开场音效</span><br><span class="line">     3.我方坦克发射子弹添加音效</span><br></pre></td></tr></table></figure>
<h3 id="坦克大战完整代码"><a href="#坦克大战完整代码" class="headerlink" title="坦克大战完整代码"></a>坦克大战完整代码</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br><span class="line">430</span><br><span class="line">431</span><br><span class="line">432</span><br><span class="line">433</span><br><span class="line">434</span><br><span class="line">435</span><br><span class="line">436</span><br><span class="line">437</span><br><span class="line">438</span><br><span class="line">439</span><br><span class="line">440</span><br><span class="line">441</span><br><span class="line">442</span><br><span class="line">443</span><br><span class="line">444</span><br><span class="line">445</span><br><span class="line">446</span><br><span class="line">447</span><br><span class="line">448</span><br><span class="line">449</span><br><span class="line">450</span><br><span class="line">451</span><br><span class="line">452</span><br><span class="line">453</span><br><span class="line">454</span><br><span class="line">455</span><br><span class="line">456</span><br><span class="line">457</span><br><span class="line">458</span><br><span class="line">459</span><br><span class="line">460</span><br><span class="line">461</span><br><span class="line">462</span><br><span class="line">463</span><br><span class="line">464</span><br><span class="line">465</span><br><span class="line">466</span><br><span class="line">467</span><br><span class="line">468</span><br><span class="line">469</span><br><span class="line">470</span><br><span class="line">471</span><br><span class="line">472</span><br><span class="line">473</span><br><span class="line">474</span><br><span class="line">475</span><br><span class="line">476</span><br><span class="line">477</span><br><span class="line">478</span><br><span class="line">479</span><br><span class="line">480</span><br><span class="line">481</span><br><span class="line">482</span><br><span class="line">483</span><br><span class="line">484</span><br><span class="line">485</span><br><span class="line">486</span><br><span class="line">487</span><br><span class="line">488</span><br><span class="line">489</span><br><span class="line">490</span><br><span class="line">491</span><br><span class="line">492</span><br><span class="line">493</span><br><span class="line">494</span><br><span class="line">495</span><br><span class="line">496</span><br><span class="line">497</span><br><span class="line">498</span><br><span class="line">499</span><br><span class="line">500</span><br><span class="line">501</span><br><span class="line">502</span><br><span class="line">503</span><br><span class="line">504</span><br><span class="line">505</span><br><span class="line">506</span><br><span class="line">507</span><br><span class="line">508</span><br><span class="line">509</span><br><span class="line">510</span><br><span class="line">511</span><br><span class="line">512</span><br><span class="line">513</span><br><span class="line">514</span><br><span class="line">515</span><br><span class="line">516</span><br><span class="line">517</span><br><span class="line">518</span><br><span class="line">519</span><br><span class="line">520</span><br><span class="line">521</span><br><span class="line">522</span><br><span class="line">523</span><br><span class="line">524</span><br><span class="line">525</span><br><span class="line">526</span><br><span class="line">527</span><br><span class="line">528</span><br><span class="line">529</span><br><span class="line">530</span><br><span class="line">531</span><br><span class="line">532</span><br><span class="line">533</span><br><span class="line">534</span><br><span class="line">535</span><br><span class="line">536</span><br><span class="line">537</span><br><span class="line">538</span><br><span class="line">539</span><br><span class="line">540</span><br><span class="line">541</span><br><span class="line">542</span><br><span class="line">543</span><br><span class="line">544</span><br><span class="line">545</span><br><span class="line">546</span><br><span class="line">547</span><br><span class="line">548</span><br><span class="line">549</span><br><span class="line">550</span><br><span class="line">551</span><br><span class="line">552</span><br><span class="line">553</span><br><span class="line">554</span><br><span class="line">555</span><br><span class="line">556</span><br><span class="line">557</span><br><span class="line">558</span><br><span class="line">559</span><br><span class="line">560</span><br><span class="line">561</span><br><span class="line">562</span><br><span class="line">563</span><br><span class="line">564</span><br><span class="line">565</span><br><span class="line">566</span><br><span class="line">567</span><br><span class="line">568</span><br><span class="line">569</span><br><span class="line">570</span><br><span class="line">571</span><br><span class="line">572</span><br><span class="line">573</span><br><span class="line">574</span><br><span class="line">575</span><br><span class="line">576</span><br><span class="line">577</span><br><span class="line">578</span><br><span class="line">579</span><br><span class="line">580</span><br><span class="line">581</span><br><span class="line">582</span><br><span class="line">583</span><br><span class="line">584</span><br><span class="line">585</span><br><span class="line">586</span><br><span class="line">587</span><br><span class="line">588</span><br><span class="line">589</span><br><span class="line">590</span><br><span class="line">591</span><br><span class="line">592</span><br><span class="line">593</span><br><span class="line">594</span><br><span class="line">595</span><br><span class="line">596</span><br><span class="line">597</span><br><span class="line">598</span><br><span class="line">599</span><br><span class="line">600</span><br><span class="line">601</span><br><span class="line">602</span><br><span class="line">603</span><br><span class="line">604</span><br><span class="line">605</span><br><span class="line">606</span><br><span class="line">607</span><br><span class="line">608</span><br><span class="line">609</span><br><span class="line">610</span><br><span class="line">611</span><br><span class="line">612</span><br><span class="line">613</span><br><span class="line">614</span><br><span class="line">615</span><br><span class="line">616</span><br><span class="line">617</span><br><span class="line">618</span><br><span class="line">619</span><br><span class="line">620</span><br><span class="line">621</span><br><span class="line">622</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">pygame模块的安装</span></span><br><span class="line"><span class="string">面向对象分析项目需求</span></span><br><span class="line"><span class="string">坦克大战项目框架搭建</span></span><br><span class="line"><span class="string">加载主窗口</span></span><br><span class="line"><span class="string">坦克大战之事件处理</span></span><br><span class="line"><span class="string">左上角文字的绘制</span></span><br><span class="line"><span class="string">加载我方坦克</span></span><br><span class="line"><span class="string">我方坦克切换方向移动</span></span><br><span class="line"><span class="string">我方坦克移动优化</span></span><br><span class="line"><span class="string">我方坦克优化2</span></span><br><span class="line"><span class="string">加载敌方坦克</span></span><br><span class="line"><span class="string">敌方坦克随机移动</span></span><br><span class="line"><span class="string">完善子单类</span></span><br><span class="line"><span class="string">我方坦克发射子弹</span></span><br><span class="line"><span class="string">子弹移动</span></span><br><span class="line"><span class="string">子弹消亡及数量控制</span></span><br><span class="line"><span class="string">敌方坦克发射子弹</span></span><br><span class="line"><span class="string">我方子弹与敌方坦克的碰撞</span></span><br><span class="line"><span class="string">实现爆炸效果</span></span><br><span class="line"><span class="string">我方坦克的消亡</span></span><br><span class="line"><span class="string">我方坦克无限重生</span></span><br><span class="line"><span class="string">加载墙壁</span></span><br><span class="line"><span class="string">子弹不穿墙</span></span><br><span class="line"><span class="string">坦克不能穿墙</span></span><br><span class="line"><span class="string">敌我双方坦克发生碰撞</span></span><br><span class="line"><span class="string">音效处理</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">import</span> pygame, time, random</span><br><span class="line"><span class="keyword">from</span> pygame.sprite <span class="keyword">import</span> Sprite</span><br><span class="line"></span><br><span class="line">SCREEN_WIDTH = <span class="number">800</span></span><br><span class="line">SCREEN_HEIGHT = <span class="number">500</span></span><br><span class="line">BG_COLOR = pygame.Color(<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>)</span><br><span class="line">TEXT_COLOR = pygame.Color(<span class="number">255</span>, <span class="number">0</span>, <span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BaseItem</span>(<span class="title class_ inherited__">Sprite</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, color, width, height</span>):</span><br><span class="line">        pygame.sprite.Sprite.__init__(self)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MainGame</span>():</span><br><span class="line">    window = <span class="literal">None</span></span><br><span class="line">    my_tank = <span class="literal">None</span></span><br><span class="line">    <span class="comment"># 存储敌方坦克的列表</span></span><br><span class="line">    enemyTankList = []</span><br><span class="line">    <span class="comment"># 定义生成敌方坦克的数量</span></span><br><span class="line">    enemyTankCount = <span class="number">5</span></span><br><span class="line">    <span class="comment"># 存储我方子弹的列表</span></span><br><span class="line">    myBulletList = []</span><br><span class="line">    <span class="comment"># 存储敌方子弹的列表</span></span><br><span class="line">    enemyBulletList = []</span><br><span class="line">    <span class="comment"># 存储爆炸效果的列表</span></span><br><span class="line">    explodeList = []</span><br><span class="line">    <span class="comment"># 存储墙壁的列表</span></span><br><span class="line">    wallList = []</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">startGame</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 加载主窗口</span></span><br><span class="line">        <span class="comment"># 初始化窗口</span></span><br><span class="line">        pygame.display.init()</span><br><span class="line">        <span class="comment"># 设置窗口的大小和显示</span></span><br><span class="line">        MainGame.window = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])</span><br><span class="line">        <span class="comment"># 初始化我方坦克</span></span><br><span class="line">        self.createMyTank()</span><br><span class="line">        <span class="comment"># 初始化敌方坦克，并将敌方坦克添加到列表中</span></span><br><span class="line">        self.createEnemyTank()</span><br><span class="line">        <span class="comment"># 初始化墙壁</span></span><br><span class="line">        self.createWall()</span><br><span class="line">        <span class="comment"># 设置窗口的标题</span></span><br><span class="line">        pygame.display.set_caption(<span class="string">&quot;坦克大战&quot;</span>)</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            <span class="comment"># 使坦克移动的速度慢一点</span></span><br><span class="line">            time.sleep(<span class="number">0.02</span>)</span><br><span class="line">            <span class="comment"># 给窗口设置填充色</span></span><br><span class="line">            MainGame.window.fill(BG_COLOR)</span><br><span class="line">            <span class="comment"># 获取事件</span></span><br><span class="line">            self.getEvent()</span><br><span class="line">            <span class="comment"># 绘制文字</span></span><br><span class="line">            MainGame.window.blit(self.getTextSuface(<span class="string">&quot;敌方坦克剩余数量%d&quot;</span> % <span class="built_in">len</span>(MainGame.enemyTankList)), (<span class="number">10</span>, <span class="number">10</span>))</span><br><span class="line">            <span class="comment"># 调用显示坦克的方法</span></span><br><span class="line">            <span class="comment"># 判断我方坦克是否是存活</span></span><br><span class="line">            <span class="keyword">if</span> MainGame.my_tank <span class="keyword">and</span> MainGame.my_tank.live:</span><br><span class="line">                MainGame.my_tank.displayTank()</span><br><span class="line">            <span class="comment"># 删否则除我方坦克</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">del</span> MainGame.my_tank</span><br><span class="line">                MainGame.my_tank = <span class="literal">None</span></span><br><span class="line">            <span class="comment"># 循环遍历敌方坦克列表，展示敌方坦克</span></span><br><span class="line">            self.blitEnemyTank()</span><br><span class="line">            <span class="comment"># 循环遍历显示我方坦克的子弹</span></span><br><span class="line">            self.blitMyBullet()</span><br><span class="line">            <span class="comment"># 循环遍历显示敌方坦克的子弹</span></span><br><span class="line">            self.blitEnemyBullet()</span><br><span class="line">            <span class="comment"># 循环遍历爆炸列表,展示爆炸效果</span></span><br><span class="line">            self.blitExplode()</span><br><span class="line">            <span class="comment"># 循环遍历墙壁列表,展示墙壁</span></span><br><span class="line">            self.blitWall()</span><br><span class="line">            <span class="comment"># 调用坦克移动的方法</span></span><br><span class="line">            <span class="comment"># 如果坦克的开关是开启,才可以移动</span></span><br><span class="line">            <span class="keyword">if</span> MainGame.my_tank <span class="keyword">and</span> MainGame.my_tank.live:</span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> MainGame.my_tank.stop:</span><br><span class="line">                    MainGame.my_tank.move()</span><br><span class="line">                    <span class="comment"># 检查我方坦克是否与墙壁发生碰撞</span></span><br><span class="line">                    MainGame.my_tank.hitWall()</span><br><span class="line">                    <span class="comment"># 检测我方坦克是否与敌方坦克发生碰撞</span></span><br><span class="line">                    MainGame.my_tank.myTank_hit_enemyTank()</span><br><span class="line"></span><br><span class="line">            pygame.display.update()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 初始化我方坦克</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createMyTank</span>(<span class="params">self</span>):</span><br><span class="line">        MainGame.my_tank = MyTank(<span class="number">350</span>, <span class="number">300</span>)</span><br><span class="line">        <span class="comment"># 创建music对象</span></span><br><span class="line">        music = Music(<span class="string">&quot;./img/start.wav&quot;</span>)</span><br><span class="line">        <span class="comment"># 播放音乐</span></span><br><span class="line">        music.play()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 初始化敌方坦克，并将敌方坦克添加到列表中</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createEnemyTank</span>(<span class="params">self</span>):</span><br><span class="line">        top = <span class="number">100</span></span><br><span class="line">        <span class="comment"># 循环生成敌方坦克</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(MainGame.enemyTankCount):</span><br><span class="line">            left = random.randint(<span class="number">0</span>, <span class="number">600</span>)</span><br><span class="line">            speed = random.randint(<span class="number">0</span>, <span class="number">4</span>)</span><br><span class="line">            enemy = EnemyTank(left, top, speed)</span><br><span class="line">            MainGame.enemyTankList.append(enemy)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 初始化墙壁</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createWall</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">6</span>):</span><br><span class="line">            <span class="comment"># 初始化墙壁</span></span><br><span class="line">            wall = Wall(i * <span class="number">130</span>, <span class="number">220</span>)</span><br><span class="line">            <span class="comment"># 将墙壁添加到列表中</span></span><br><span class="line">            MainGame.wallList.append(wall)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 循环遍历敌方坦克列表，展示敌方坦克</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">blitEnemyTank</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> enemyTank <span class="keyword">in</span> MainGame.enemyTankList:</span><br><span class="line">            <span class="comment"># 判断敌方坦克是否活着</span></span><br><span class="line">            <span class="keyword">if</span> enemyTank.live:</span><br><span class="line">                enemyTank.displayTank()</span><br><span class="line">                enemyTank.randMove()</span><br><span class="line">                <span class="comment"># 调用检测敌方坦克是否和墙壁碰撞</span></span><br><span class="line">                enemyTank.hitWall()</span><br><span class="line">                <span class="comment"># 检测敌方坦克是否和我方坦克发生碰撞</span></span><br><span class="line">                <span class="keyword">if</span> MainGame.my_tank <span class="keyword">and</span> MainGame.my_tank.live:</span><br><span class="line">                    enemyTank.enemyTank_hit_myTank()</span><br><span class="line">                <span class="comment"># 发射子弹</span></span><br><span class="line">                enemyBullet = enemyTank.shot()</span><br><span class="line">                <span class="comment"># 敌方子弹是否为None,如果不为None则添加到敌方子弹列表</span></span><br><span class="line">                <span class="keyword">if</span> enemyBullet:</span><br><span class="line">                    <span class="comment"># 将敌方坦克子弹存储到敌方子弹列表中</span></span><br><span class="line">                    MainGame.enemyBulletList.append(enemyBullet)</span><br><span class="line">            <span class="comment"># 从敌方坦克列表移除</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                MainGame.enemyTankList.remove(enemyTank)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 循环遍历我方坦克的子弹存储列表</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">blitMyBullet</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> myBullet <span class="keyword">in</span> MainGame.myBulletList:</span><br><span class="line">            <span class="comment"># 判断当前子弹是否是活着的状态，如果是则进行显示及移动</span></span><br><span class="line">            <span class="keyword">if</span> myBullet.live:</span><br><span class="line">                myBullet.displayBullet()</span><br><span class="line">                <span class="comment"># 调用子弹的移动方法</span></span><br><span class="line">                myBullet.move()</span><br><span class="line">                <span class="comment"># 调用检测我方子弹是否和敌方坦克发生碰撞</span></span><br><span class="line">                myBullet.myBullet_hit_enemyTank()</span><br><span class="line">                <span class="comment"># 检测我方子弹是否和墙壁碰撞</span></span><br><span class="line">                myBullet.hitWall()</span><br><span class="line">            <span class="comment"># 否则在列表中删除</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                MainGame.myBulletList.remove(myBullet)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 循环遍历显示敌方坦克的子弹</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">blitEnemyBullet</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> enemyBullet <span class="keyword">in</span> MainGame.enemyBulletList:</span><br><span class="line">            <span class="comment"># 判断当前子弹是否是活着的状态，如果是则进行显示及移动</span></span><br><span class="line">            <span class="keyword">if</span> enemyBullet.live:</span><br><span class="line">                enemyBullet.displayBullet()</span><br><span class="line">                <span class="comment"># 调用子弹的移动方法</span></span><br><span class="line">                enemyBullet.move()</span><br><span class="line">                <span class="comment"># 调用检测敌方子弹是否和我方坦克发生碰撞</span></span><br><span class="line">                enemyBullet.enemyBullet_hit_myTank()</span><br><span class="line">                <span class="comment"># 检测敌方子弹是否和墙壁碰撞</span></span><br><span class="line">                enemyBullet.hitWall()</span><br><span class="line">            <span class="comment"># 否则在列表中删除</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                MainGame.enemyBulletList.remove(enemyBullet)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 循环遍历爆炸列表,展示爆炸效果</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">blitExplode</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> explode <span class="keyword">in</span> MainGame.explodeList:</span><br><span class="line">            <span class="comment"># 判断是否是活着的状态，如果是则进行显示</span></span><br><span class="line">            <span class="keyword">if</span> explode.live:</span><br><span class="line">                explode.displayExplode()</span><br><span class="line">                <span class="comment"># 添加爆炸音效</span></span><br><span class="line">                music = Music(<span class="string">&quot;./img/fire.wav&quot;</span>)</span><br><span class="line">                music.play()</span><br><span class="line">            <span class="comment"># 否则在爆炸列表中删除</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                MainGame.explodeList.remove(explode)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 循环遍历墙壁列表,展示墙壁</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">blitWall</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> wall <span class="keyword">in</span> MainGame.wallList:</span><br><span class="line">            <span class="comment"># 判断墙壁是否存活</span></span><br><span class="line">            <span class="keyword">if</span> wall.live:</span><br><span class="line">                <span class="comment"># 调用墙壁展示方法</span></span><br><span class="line">                wall.displayWall()</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment"># 从墙壁列表移除</span></span><br><span class="line">                MainGame.wallList.remove(wall)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">endGame</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;感谢使用，欢迎再次使用&quot;</span>)</span><br><span class="line">        exit()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 左上角文字绘制</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getTextSuface</span>(<span class="params">self, text</span>):</span><br><span class="line">        <span class="comment"># 初始化字体模块</span></span><br><span class="line">        pygame.font.init()</span><br><span class="line">        <span class="comment"># 查看所有字体名称</span></span><br><span class="line">        <span class="comment"># print(pygame.font.get_fonts())</span></span><br><span class="line">        <span class="comment"># 获取字体font对象</span></span><br><span class="line">        font = pygame.font.SysFont(<span class="string">&quot;adobe宋体stdl&quot;</span>, <span class="number">18</span>)</span><br><span class="line">        <span class="comment"># 绘制字体信息</span></span><br><span class="line">        textSurface = font.render(text, <span class="literal">True</span>, TEXT_COLOR)</span><br><span class="line">        <span class="keyword">return</span> textSurface</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getEvent</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 获取事件</span></span><br><span class="line">        eventList = pygame.event.get()</span><br><span class="line">        <span class="comment"># 遍历事件</span></span><br><span class="line">        <span class="keyword">for</span> event <span class="keyword">in</span> eventList:</span><br><span class="line">            <span class="comment"># 判断按下的键是关闭还是键盘按下</span></span><br><span class="line">            <span class="comment"># 如果按的是退出，关闭窗口</span></span><br><span class="line">            <span class="keyword">if</span> event.<span class="built_in">type</span> == pygame.QUIT:</span><br><span class="line">                self.endGame()</span><br><span class="line">            <span class="comment"># 如果是键盘的按下</span></span><br><span class="line">            <span class="keyword">if</span> event.<span class="built_in">type</span> == pygame.KEYDOWN:</span><br><span class="line">                <span class="comment"># 当坦克死亡或不存在</span></span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> MainGame.my_tank:</span><br><span class="line">                    <span class="comment"># 如果按下的是ESC键,让我方坦克重生</span></span><br><span class="line">                    <span class="keyword">if</span> event.key == pygame.K_ESCAPE:</span><br><span class="line">                        <span class="comment"># 让我方坦克重生及调用创建坦克的方法</span></span><br><span class="line">                        self.createMyTank()</span><br><span class="line">                <span class="keyword">if</span> MainGame.my_tank <span class="keyword">and</span> MainGame.my_tank.live:</span><br><span class="line">                    <span class="comment"># 判断的是按下的上、下、左、右</span></span><br><span class="line">                    <span class="keyword">if</span> event.key == pygame.K_LEFT:</span><br><span class="line">                        <span class="comment"># 切换方向</span></span><br><span class="line">                        MainGame.my_tank.direction = <span class="string">&quot;L&quot;</span></span><br><span class="line">                        <span class="comment"># MainGame.my_tank.move()</span></span><br><span class="line">                        <span class="comment"># 修改坦克的的开关</span></span><br><span class="line">                        MainGame.my_tank.stop = <span class="literal">False</span></span><br><span class="line">                        <span class="built_in">print</span>(<span class="string">&quot;按下左键，坦克左移&quot;</span>)</span><br><span class="line">                    <span class="keyword">elif</span> event.key == pygame.K_RIGHT:</span><br><span class="line">                        <span class="comment"># 切换方向</span></span><br><span class="line">                        MainGame.my_tank.direction = <span class="string">&quot;R&quot;</span></span><br><span class="line">                        <span class="comment"># MainGame.my_tank.move()</span></span><br><span class="line">                        <span class="comment"># 修改坦克的的开关</span></span><br><span class="line">                        MainGame.my_tank.stop = <span class="literal">False</span></span><br><span class="line">                        <span class="built_in">print</span>(<span class="string">&quot;按下右键，坦克右移&quot;</span>)</span><br><span class="line">                    <span class="keyword">elif</span> event.key == pygame.K_UP:</span><br><span class="line">                        <span class="comment"># 切换方向</span></span><br><span class="line">                        MainGame.my_tank.direction = <span class="string">&quot;U&quot;</span></span><br><span class="line">                        <span class="comment"># MainGame.my_tank.move()</span></span><br><span class="line">                        <span class="comment"># 修改坦克的的开关</span></span><br><span class="line">                        MainGame.my_tank.stop = <span class="literal">False</span></span><br><span class="line">                        <span class="built_in">print</span>(<span class="string">&quot;按下上键，坦克上移&quot;</span>)</span><br><span class="line">                    <span class="keyword">elif</span> event.key == pygame.K_DOWN:</span><br><span class="line">                        <span class="comment"># 切换方向</span></span><br><span class="line">                        MainGame.my_tank.direction = <span class="string">&quot;D&quot;</span></span><br><span class="line">                        <span class="comment"># 修改坦克的的开关</span></span><br><span class="line">                        MainGame.my_tank.stop = <span class="literal">False</span></span><br><span class="line">                        <span class="comment"># MainGame.my_tank.move()</span></span><br><span class="line">                        <span class="built_in">print</span>(<span class="string">&quot;按下下键，坦克下移&quot;</span>)</span><br><span class="line">                    <span class="keyword">elif</span> event.key == pygame.K_SPACE:</span><br><span class="line">                        <span class="built_in">print</span>(<span class="string">&quot;发射子弹&quot;</span>)</span><br><span class="line">                        <span class="comment"># 如果当前我方子弹列表的大小&lt;3时候才可以创建</span></span><br><span class="line">                        <span class="keyword">if</span> <span class="built_in">len</span>(MainGame.myBulletList) &lt; <span class="number">3</span>:</span><br><span class="line">                            <span class="comment"># 创建我方坦克发射的子弹</span></span><br><span class="line">                            myBullet = Bullet(MainGame.my_tank)</span><br><span class="line">                            MainGame.myBulletList.append(myBullet)</span><br><span class="line">                            <span class="comment"># 我方坦克发射子弹添加音效</span></span><br><span class="line">                            music = Music(<span class="string">&quot;./img/hit.wav&quot;</span>)</span><br><span class="line">                            music.play()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 松开方向键,坦克移动停止,修改坦克开关状态</span></span><br><span class="line">            <span class="keyword">if</span> event.<span class="built_in">type</span> == pygame.KEYUP:</span><br><span class="line">                <span class="comment"># 判断松开的键是上、下、左、右的时候才停止坦克移动</span></span><br><span class="line">                <span class="keyword">if</span> event.key == pygame.K_LEFT <span class="keyword">or</span> event.key == pygame.K_RIGHT <span class="keyword">or</span> event.key == pygame.K_UP <span class="keyword">or</span> event.key == pygame.K_DOWN:</span><br><span class="line">                    <span class="keyword">if</span> MainGame.my_tank <span class="keyword">and</span> MainGame.my_tank.live:</span><br><span class="line">                        MainGame.my_tank.stop = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 坦克类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Tank</span>(<span class="title class_ inherited__">BaseItem</span>):</span><br><span class="line">    <span class="comment"># 添加距离左边left 距离上边top</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, left, top</span>):</span><br><span class="line">        <span class="comment"># 加载保存的图片</span></span><br><span class="line">        self.images = &#123;</span><br><span class="line">            <span class="string">&quot;U&quot;</span>: pygame.image.load(<span class="string">&quot;./img/p1tankU.gif&quot;</span>),</span><br><span class="line">            <span class="string">&quot;D&quot;</span>: pygame.image.load(<span class="string">&quot;./img/p1tankD.gif&quot;</span>),</span><br><span class="line">            <span class="string">&quot;L&quot;</span>: pygame.image.load(<span class="string">&quot;./img/p1tankL.gif&quot;</span>),</span><br><span class="line">            <span class="string">&quot;R&quot;</span>: pygame.image.load(<span class="string">&quot;./img/p1tankR.gif&quot;</span>),</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment"># 方向</span></span><br><span class="line">        self.direction = <span class="string">&quot;U&quot;</span></span><br><span class="line">        <span class="comment"># 根据当前图片的方向获取图片</span></span><br><span class="line">        self.image = self.images[self.direction]</span><br><span class="line">        <span class="comment"># 根据图片获取区域</span></span><br><span class="line">        self.rect = self.image.get_rect()</span><br><span class="line">        <span class="comment"># 设置区域的left和top</span></span><br><span class="line">        self.rect.left = left</span><br><span class="line">        self.rect.top = top</span><br><span class="line">        <span class="comment"># 速度决定移动的快慢</span></span><br><span class="line">        self.speed = <span class="number">5</span></span><br><span class="line">        <span class="comment"># 坦克移动的开关</span></span><br><span class="line">        self.stop = <span class="literal">True</span></span><br><span class="line">        <span class="comment"># 是否存活</span></span><br><span class="line">        self.live = <span class="literal">True</span></span><br><span class="line">        <span class="comment"># 新增属性原来坐标</span></span><br><span class="line">        self.oldLeft = self.rect.left</span><br><span class="line">        self.oldTop = self.rect.top</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 移动</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">move</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 移动后记录原始的坐标</span></span><br><span class="line">        self.oldLeft = self.rect.left</span><br><span class="line">        self.oldTop = self.rect.top</span><br><span class="line">        <span class="comment"># 判断坦克的方向进行移动</span></span><br><span class="line">        <span class="keyword">if</span> self.direction == <span class="string">&quot;L&quot;</span>:</span><br><span class="line">            <span class="comment"># 判断是否超过边界</span></span><br><span class="line">            <span class="keyword">if</span> self.rect.left &gt; <span class="number">0</span>:</span><br><span class="line">                self.rect.left -= self.speed</span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;R&quot;</span>:</span><br><span class="line">            <span class="comment"># 判断是否超过边界</span></span><br><span class="line">            <span class="keyword">if</span> self.rect.left + self.rect.height &lt; SCREEN_WIDTH:</span><br><span class="line">                self.rect.left += self.speed</span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;U&quot;</span>:</span><br><span class="line">            <span class="comment"># 判断是否超过边界</span></span><br><span class="line">            <span class="keyword">if</span> self.rect.top &gt; <span class="number">0</span>:</span><br><span class="line">                self.rect.top -= self.speed</span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;D&quot;</span>:</span><br><span class="line">            <span class="comment"># 判断是否超过边界</span></span><br><span class="line">            <span class="keyword">if</span> self.rect.top + self.rect.height &lt; SCREEN_HEIGHT:</span><br><span class="line">                self.rect.top += self.speed</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 射击</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">shot</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> Bullet(self)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stay</span>(<span class="params">self</span>):</span><br><span class="line">        self.rect.left = self.oldLeft</span><br><span class="line">        self.rect.top = self.oldTop</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 检查坦克是否和墙壁发生碰撞</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hitWall</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> wall <span class="keyword">in</span> MainGame.wallList:</span><br><span class="line">            <span class="keyword">if</span> pygame.sprite.collide_rect(self, wall):</span><br><span class="line">                <span class="comment"># 将坐标设置移动之前的坐标</span></span><br><span class="line">                self.stay()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 展示坦克的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayTank</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 获取展示对象</span></span><br><span class="line">        self.image = self.images[self.direction]</span><br><span class="line">        <span class="comment"># 调用blit方法展示</span></span><br><span class="line">        MainGame.window.blit(self.image, self.rect)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 我方坦克</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyTank</span>(<span class="title class_ inherited__">Tank</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, left, top</span>):</span><br><span class="line">        <span class="built_in">super</span>(MyTank, self).__init__(left, top)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 检测我方坦克是否与敌方坦克发生碰撞</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myTank_hit_enemyTank</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 循环遍历敌方坦克列表</span></span><br><span class="line">        <span class="keyword">for</span> enemyTank <span class="keyword">in</span> MainGame.enemyTankList:</span><br><span class="line">            <span class="keyword">if</span> pygame.sprite.collide_rect(self, enemyTank):</span><br><span class="line">                self.stay()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 敌方坦克</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">EnemyTank</span>(<span class="title class_ inherited__">Tank</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, left, top, speed</span>):</span><br><span class="line">        <span class="comment"># 调用父类的初始化方法</span></span><br><span class="line">        <span class="built_in">super</span>(EnemyTank, self).__init__(left, top)</span><br><span class="line">        <span class="comment"># 加载啊图片集</span></span><br><span class="line">        self.images = &#123;</span><br><span class="line">            <span class="string">&quot;U&quot;</span>: pygame.image.load(<span class="string">&quot;./img/enemy1U.gif&quot;</span>),</span><br><span class="line">            <span class="string">&quot;D&quot;</span>: pygame.image.load(<span class="string">&quot;./img/enemy1D.gif&quot;</span>),</span><br><span class="line">            <span class="string">&quot;R&quot;</span>: pygame.image.load(<span class="string">&quot;./img/enemy1R.gif&quot;</span>),</span><br><span class="line">            <span class="string">&quot;L&quot;</span>: pygame.image.load(<span class="string">&quot;./img/enemy1L.gif&quot;</span>),</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment"># 方向，随机生成敌方坦克的方向</span></span><br><span class="line">        self.direction = self.randDirection()</span><br><span class="line">        <span class="comment"># 根据方向获取图片</span></span><br><span class="line">        self.image = self.images[self.direction]</span><br><span class="line">        <span class="comment"># 根据图片获取区域</span></span><br><span class="line">        self.rect = self.image.get_rect()</span><br><span class="line">        <span class="comment"># 设置区域的left和top</span></span><br><span class="line">        self.rect.left = left</span><br><span class="line">        self.rect.top = top</span><br><span class="line">        <span class="comment"># 速度决定移动的快慢</span></span><br><span class="line">        self.speed = <span class="number">5</span></span><br><span class="line">        <span class="comment"># 坦克移动的开关</span></span><br><span class="line">        self.stop = <span class="literal">True</span></span><br><span class="line">        <span class="comment"># 新增加一个步数变量 step</span></span><br><span class="line">        self.step = <span class="number">50</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 随机生成敌方坦克的方向</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">randDirection</span>(<span class="params">self</span>):</span><br><span class="line">        num = random.randint(<span class="number">1</span>, <span class="number">4</span>)</span><br><span class="line">        <span class="keyword">if</span> num == <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;U&quot;</span></span><br><span class="line">        <span class="keyword">elif</span> num == <span class="number">2</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;D&quot;</span></span><br><span class="line">        <span class="keyword">elif</span> num == <span class="number">3</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;L&quot;</span></span><br><span class="line">        <span class="keyword">elif</span> num == <span class="number">4</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;R&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">randMove</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> self.step &lt;= <span class="number">0</span>:</span><br><span class="line">            <span class="comment"># 修改方向</span></span><br><span class="line">            self.direction = self.randDirection()</span><br><span class="line">            <span class="comment"># 让步数复位</span></span><br><span class="line">            self.step = <span class="number">50</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.move()</span><br><span class="line">            <span class="comment"># 让步数递减</span></span><br><span class="line">            self.step -= <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 重写shot()</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">shot</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 随机生成100以内的数</span></span><br><span class="line">        num = random.randint(<span class="number">1</span>, <span class="number">100</span>)</span><br><span class="line">        <span class="keyword">if</span> num &lt; <span class="number">10</span>:</span><br><span class="line">            <span class="keyword">return</span> Bullet(self)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 检测敌方坦克是否和我方坦克发生碰撞</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">enemyTank_hit_myTank</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> pygame.sprite.collide_rect(self, MainGame.my_tank):</span><br><span class="line">            self.stay()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 子弹类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Bullet</span>(<span class="title class_ inherited__">BaseItem</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, tank</span>):</span><br><span class="line">        <span class="comment"># 加载图片</span></span><br><span class="line">        self.image = pygame.image.load(<span class="string">&quot;./img/enemymissile.gif&quot;</span>)</span><br><span class="line">        <span class="comment"># 坦克的方向决定子弹的方向</span></span><br><span class="line">        self.direction = tank.direction</span><br><span class="line">        <span class="comment"># 获取区域</span></span><br><span class="line">        self.rect = self.image.get_rect()</span><br><span class="line">        <span class="comment"># 子弹的left和top和方向有关</span></span><br><span class="line">        <span class="keyword">if</span> self.direction == <span class="string">&quot;U&quot;</span>:</span><br><span class="line">            self.rect.left = tank.rect.left + tank.rect.width / <span class="number">2</span> - self.rect.width / <span class="number">2</span></span><br><span class="line">            self.rect.top = tank.rect.top - self.rect.height</span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;D&quot;</span>:</span><br><span class="line">            self.rect.left = tank.rect.left + tank.rect.width / <span class="number">2</span> - self.rect.width / <span class="number">2</span></span><br><span class="line">            self.rect.top = tank.rect.top + self.rect.height</span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;R&quot;</span>:</span><br><span class="line">            self.rect.left = tank.rect.left + self.rect.width</span><br><span class="line">            self.rect.top = tank.rect.top + tank.rect.width / <span class="number">2</span> - self.rect.width / <span class="number">2</span></span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;L&quot;</span>:</span><br><span class="line">            self.rect.left = tank.rect.left - tank.rect.width / <span class="number">2</span> - self.rect.width / <span class="number">2</span></span><br><span class="line">            self.rect.top = tank.rect.top + tank.rect.width / <span class="number">2</span> - self.rect.width / <span class="number">2</span></span><br><span class="line">        <span class="comment"># 子弹的速度</span></span><br><span class="line">        self.speed = <span class="number">6</span></span><br><span class="line">        <span class="comment"># 子弹的状态，是否碰到墙壁，如果碰到墙壁，修改此状态</span></span><br><span class="line">        self.live = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 移动</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">move</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 子弹的移动和方向有关</span></span><br><span class="line">        <span class="keyword">if</span> self.direction == <span class="string">&quot;U&quot;</span>:</span><br><span class="line">            <span class="keyword">if</span> self.rect.top &gt; <span class="number">0</span>:</span><br><span class="line">                self.rect.top -= self.speed</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment"># 修改子弹状态</span></span><br><span class="line">                self.live = <span class="literal">False</span></span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;D&quot;</span>:</span><br><span class="line">            <span class="keyword">if</span> self.rect.top + self.rect.height &lt; SCREEN_HEIGHT:</span><br><span class="line">                self.rect.top += self.speed</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment"># 修改子弹状态</span></span><br><span class="line">                self.live = <span class="literal">False</span></span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;R&quot;</span>:</span><br><span class="line">            <span class="keyword">if</span> self.rect.left + self.rect.width &lt; SCREEN_WIDTH:</span><br><span class="line">                self.rect.left += self.speed</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment"># 修改子弹状态</span></span><br><span class="line">                self.live = <span class="literal">False</span></span><br><span class="line">        <span class="keyword">elif</span> self.direction == <span class="string">&quot;L&quot;</span>:</span><br><span class="line">            <span class="keyword">if</span> self.rect.left &gt; <span class="number">0</span>:</span><br><span class="line">                self.rect.left -= self.speed</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment"># 修改子弹状态</span></span><br><span class="line">                self.live = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">                <span class="comment"># 展示子弹的方法</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 子弹是否碰撞墙壁</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hitWall</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> wall <span class="keyword">in</span> MainGame.wallList:</span><br><span class="line">            <span class="keyword">if</span> pygame.sprite.collide_rect(self, wall):</span><br><span class="line">                <span class="comment"># 修改子弹的生存状态,让子弹消失</span></span><br><span class="line">                self.live = <span class="literal">False</span></span><br><span class="line">                <span class="comment"># 墙壁的生命值减小</span></span><br><span class="line">                wall.hp -= <span class="number">1</span></span><br><span class="line">                <span class="keyword">if</span> wall.hp &lt; <span class="number">0</span>:</span><br><span class="line">                    <span class="comment"># 修改墙壁的生存状态</span></span><br><span class="line">                    wall.live = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayBullet</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 将图片surface加载到窗口</span></span><br><span class="line">        MainGame.window.blit(self.image, self.rect)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 我方子弹和敌方坦克碰撞</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myBullet_hit_enemyTank</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># 循环遍历敌方坦克列表,判断是否发生碰撞</span></span><br><span class="line">        <span class="keyword">for</span> enemyTank <span class="keyword">in</span> MainGame.enemyTankList:</span><br><span class="line">            <span class="keyword">if</span> pygame.sprite.collide_rect(enemyTank, self):</span><br><span class="line">                <span class="comment"># 修改敌方坦克和我方子弹的状态</span></span><br><span class="line">                enemyTank.live = <span class="literal">False</span></span><br><span class="line">                self.live = <span class="literal">False</span></span><br><span class="line">                <span class="comment"># 创建爆炸对象</span></span><br><span class="line">                explode = Expode(enemyTank)</span><br><span class="line">                <span class="comment"># 将爆炸对象添加到爆炸列表中</span></span><br><span class="line">                MainGame.explodeList.append(explode)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 敌方子弹和我方坦克碰撞</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">enemyBullet_hit_myTank</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> MainGame.my_tank <span class="keyword">and</span> MainGame.my_tank.live:</span><br><span class="line">            <span class="keyword">if</span> pygame.sprite.collide_rect(MainGame.my_tank, self):</span><br><span class="line">                <span class="comment"># 创建爆炸对象</span></span><br><span class="line">                explode = Expode(MainGame.my_tank)</span><br><span class="line">                <span class="comment"># 将爆炸对象添加到爆炸列表中</span></span><br><span class="line">                MainGame.explodeList.append(explode)</span><br><span class="line">                <span class="comment"># 修改敌方子弹和我方坦克的状态</span></span><br><span class="line">                self.live = <span class="literal">False</span></span><br><span class="line">                MainGame.my_tank.live = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 墙壁类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Wall</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, left, top</span>):</span><br><span class="line">        <span class="comment"># 加载墙壁图片</span></span><br><span class="line">        self.image = pygame.image.load(<span class="string">&quot;./img/steels.gif&quot;</span>)</span><br><span class="line">        <span class="comment"># 获取墙壁区域</span></span><br><span class="line">        self.rect = self.image.get_rect()</span><br><span class="line">        <span class="comment"># 设置位置left和top</span></span><br><span class="line">        self.rect.left = left</span><br><span class="line">        self.rect.top = top</span><br><span class="line">        <span class="comment"># 是否存活</span></span><br><span class="line">        self.live = <span class="literal">True</span></span><br><span class="line">        <span class="comment"># 设置生命值</span></span><br><span class="line">        self.hp = <span class="number">3</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 展示墙壁的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayWall</span>(<span class="params">self</span>):</span><br><span class="line">        MainGame.window.blit(self.image, self.rect)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 爆炸类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Expode</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, tank</span>):</span><br><span class="line">        <span class="comment"># 爆炸位置由当前子弹打中的坦克位置决定</span></span><br><span class="line">        self.rect = tank.rect</span><br><span class="line">        self.images = [</span><br><span class="line">            pygame.image.load(<span class="string">&quot;./img/blast0.gif&quot;</span>),</span><br><span class="line">            pygame.image.load(<span class="string">&quot;./img/blast1.gif&quot;</span>),</span><br><span class="line">            pygame.image.load(<span class="string">&quot;./img/blast2.gif&quot;</span>),</span><br><span class="line">            pygame.image.load(<span class="string">&quot;./img/blast3.gif&quot;</span>),</span><br><span class="line">            pygame.image.load(<span class="string">&quot;./img/blast4.gif&quot;</span>),</span><br><span class="line">        ]</span><br><span class="line">        self.step = <span class="number">0</span></span><br><span class="line">        self.image = self.images[self.step]</span><br><span class="line">        <span class="comment"># 是否活着</span></span><br><span class="line">        self.live = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 展示爆炸效果的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">displayExplode</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> self.step &lt; <span class="built_in">len</span>(self.images):</span><br><span class="line">            <span class="comment"># 根据索引获取爆炸对象</span></span><br><span class="line">            self.image = self.images[self.step]</span><br><span class="line">            self.step += <span class="number">1</span></span><br><span class="line">            <span class="comment"># 添加到主窗口</span></span><br><span class="line">            MainGame.window.blit(self.image, self.rect)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 修改活着的状态</span></span><br><span class="line">            self.live = <span class="literal">False</span></span><br><span class="line">            self.step = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 音效类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Music</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, filename</span>):</span><br><span class="line">        self.filename = filename</span><br><span class="line">        <span class="comment"># 初始化音乐混合器</span></span><br><span class="line">        pygame.mixer.init()</span><br><span class="line">        <span class="comment"># 加载音乐</span></span><br><span class="line">        pygame.mixer.music.load(self.filename)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 播放音乐的方法</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">play</span>(<span class="params">self</span>):</span><br><span class="line">        pygame.mixer.music.play()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    MainGame().startGame()</span><br><span class="line">    <span class="comment"># MainGame().getTextSuface()</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://huaiyuechusan.github.io">SanShui</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://huaiyuechusan.github.io/archives/8df5f8b9.html">https://huaiyuechusan.github.io/archives/8df5f8b9.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://huaiyuechusan.github.io" target="_blank">SanShui的个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E5%AD%A6%E4%B9%A0%E6%8A%80%E6%9C%AF/">学习技术</a><a class="post-meta__tags" href="/tags/Python/">Python</a></div><div class="post_share"><div class="social-share" data-image="http://wallpaper.csun.site/?5" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/img/wechat.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/img/alipay.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/archives/7cb9f0a8.html"><img class="prev-cover" src="http://wallpaper.csun.site/?23" onerror="onerror=null;src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">通过nginx访问tomcat中SpringMVC应用</div></div></a></div><div class="next-post pull-right"><a href="/archives/984515cf.html"><img class="next-cover" src="http://wallpaper.csun.site/?6" onerror="onerror=null;src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Python 网络与并发编程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/archives/984515cf.html" title="Python 网络与并发编程"><img class="cover" src="http://wallpaper.csun.site/?6" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">Python 网络与并发编程</div></div></a></div><div><a href="/archives/fab44cdf.html" title="函数式编程和Python新核心特性"><img class="cover" src="http://wallpaper.csun.site/?7" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">函数式编程和Python新核心特性</div></div></a></div><div><a href="/archives/d9ef328.html" title="Python入门"><img class="cover" src="http://wallpaper.csun.site/?4" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">Python入门</div></div></a></div><div><a href="/archives/6d169344.html" title="云函数调用request请求"><img class="cover" src="http://wallpaper.csun.site/?21" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">云函数调用request请求</div></div></a></div><div><a href="/archives/d4b1abad.html" title="下载M3U8格式加密视频"><img class="cover" src="http://wallpaper.csun.site/?22" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">下载M3U8格式加密视频</div></div></a></div><div><a href="/archives/59cb3162.html" title="大数据集群软件启动脚本"><img class="cover" src="http://wallpaper.csun.site/?11" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">大数据集群软件启动脚本</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81OTEzMS8zNTU5Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg" onerror="this.onerror=null;this.src='/./img/config_img/%E8%93%9D%E5%A4%A9.jpg'" alt="avatar"/></div><div class="author-info__name">SanShui</div><div class="author-info__description">今天不学习，明天变垃圾</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><a id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/huaiyuechusan"><i class="fa-sharp fa-solid fa-plane"></i><span>欢迎关注我的Github</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/huaiyuechusan" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://huaiyuechusan.github.io/atom.xml" target="_blank" title=""><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到SanShui的博客</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Python%E6%B7%B1%E5%85%A5%E5%92%8C%E6%8F%90%E9%AB%98"><span class="toc-text">Python深入和提高</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%82%E5%B8%B8%E6%9C%BA%E5%88%B6"><span class="toc-text">异常机制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E5%B8%B8%E7%9A%84%E6%9C%AC%E8%B4%A8-%E8%B0%83%E8%AF%95%E9%94%99%E8%AF%AF%E7%9A%84%E6%A0%B8%E5%BF%83%E7%90%86%E5%BF%B5"><span class="toc-text">异常的本质-调试错误的核心理念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#try-except%E5%9F%BA%E6%9C%AC%E7%BB%93%E6%9E%84"><span class="toc-text">try_except基本结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#try-%E5%A4%9A%E4%B8%AAexcept%E7%BB%93%E6%9E%84"><span class="toc-text">try_多个except结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#try%E2%80%A6except%E2%80%A6else%E7%BB%93%E6%9E%84"><span class="toc-text">try…except…else结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#try%E2%80%A6except%E2%80%A6finally%E7%BB%93%E6%9E%84%E5%92%8Creturn%E8%AF%AD%E5%8F%A5%E4%BD%8D%E7%BD%AE"><span class="toc-text">try…except…finally结构和return语句位置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E5%BC%82%E5%B8%B8%E6%B1%87%E6%80%BB%E8%AF%B4%E6%98%8E"><span class="toc-text">常见异常汇总说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#with%E4%B8%8A%E4%B8%8B%E6%96%87%E7%AE%A1%E7%90%86%E8%B5%84%E6%BA%90"><span class="toc-text">with上下文管理资源</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#traceback%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8-%E5%BC%82%E5%B8%B8%E5%86%99%E5%85%A5%E6%97%A5%E5%BF%97%E6%96%87%E4%BB%B6"><span class="toc-text">traceback模块的使用-异常写入日志文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%BC%82%E5%B8%B8-raise%E6%8A%9B%E5%87%BA%E5%BC%82%E5%B8%B8"><span class="toc-text">自定义异常-raise抛出异常</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Pycharm%E8%B0%83%E8%AF%95%E6%A8%A1%E5%BC%8Fdebug%E8%A7%86%E5%9B%BE"><span class="toc-text">Pycharm调试模式debug视图</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E5%A4%84%E7%90%86"><span class="toc-text">文件处理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#fle%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E5%BA%95%E5%B1%82%E5%85%B3%E7%B3%BB-%E5%86%99%E5%85%A5%E6%96%87%E4%BB%B6"><span class="toc-text">fle文件操作-操作系统底层关系-写入文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%96%E7%A0%81%E7%9F%A5%E8%AF%86-%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3"><span class="toc-text">编码知识-中文乱码问题解决</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B3%E9%97%AD%E6%B5%81%E8%A6%81%E7%82%B9"><span class="toc-text">关闭流要点</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#finally%E5%BC%82%E5%B8%B8%E7%AE%A1%E7%90%86"><span class="toc-text">finally异常管理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#with%E4%B8%8A%E4%B8%8B%E6%96%87%E7%AE%A1%E7%90%86"><span class="toc-text">with上下文管理</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6%E7%9A%84%E8%AF%BB%E5%8F%96"><span class="toc-text">文本文件的读取</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C-%E4%B8%BA%E6%AF%8F%E8%A1%8C%E7%9A%84%E6%9C%AB%E5%B0%BE%E6%B7%BB%E5%8A%A0%E8%A1%8C%E5%8F%B7"><span class="toc-text">文本文件操作-为每行的末尾添加行号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8C%E8%BF%9B%E5%88%B6%E6%96%87%E4%BB%B6%E7%9A%84%E8%AF%BB%E5%86%99-%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6%E7%9A%84%E6%8B%B7%E8%B4%9D"><span class="toc-text">二进制文件的读写-图片文件的拷贝</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E5%AF%B9%E8%B1%A1%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95%E5%92%8C%E5%B1%9E%E6%80%A7%E6%80%BB%E7%BB%93-seek-%E4%BB%BB%E6%84%8F%E4%BD%8D%E7%BD%AE%E6%93%8D%E4%BD%9C"><span class="toc-text">文件对象常用方法和属性总结-seek()任意位置操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8pickle%E5%AE%9E%E7%8E%B0%E5%BA%8F%E5%88%97%E5%8C%96%E5%92%8C%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96"><span class="toc-text">使用pickle实现序列化和反序列化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#csv%E6%96%87%E4%BB%B6%E7%9A%84%E8%AF%BB%E5%8F%96%E5%92%8C%E5%86%99%E5%85%A5"><span class="toc-text">csv文件的读取和写入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#os%E6%A8%A1%E5%9D%97"><span class="toc-text">os模块</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B0%83%E7%94%A8%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E5%8F%AF%E6%89%A7%E8%A1%8C%E6%96%87%E4%BB%B6-%E6%8E%A7%E5%88%B6%E5%8F%B0%E4%B9%B1%E7%A0%81%E9%97%AE%E9%A2%98"><span class="toc-text">调用操作系统可执行文件-控制台乱码问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E6%96%87%E4%BB%B6%E4%BF%A1%E6%81%AF-%E5%88%9B%E5%BB%BA%E5%92%8C%E5%88%A0%E9%99%A4%E6%96%87%E4%BB%B6%E5%A4%B9"><span class="toc-text">获取文件信息-创建和删除文件夹</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#os-path%E6%A8%A1%E5%9D%97-%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-text">os.path模块-常用方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8walk%E9%80%92%E5%BD%92%E9%81%8D%E5%8E%86%E6%89%80%E6%9C%89%E5%AD%90%E7%9B%AE%E5%BD%95%E5%92%8C%E5%AD%90%E6%96%87%E4%BB%B6"><span class="toc-text">使用walk递归遍历所有子目录和子文件</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#shutil%E6%A8%A1%E5%9D%97"><span class="toc-text">shutil模块</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#shutil%E6%A8%A1%E5%9D%97%EF%BC%88%E6%8B%B7%E8%B4%9D%E5%92%8C%E5%8E%8B%E7%BC%A9%EF%BC%89"><span class="toc-text">shutil模块（拷贝和压缩）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#shutil%E5%92%8Czipfile%E6%A8%A1%E5%9D%97-%E5%8E%8B%E7%BC%A9%E5%92%8C%E8%A7%A3%E5%8E%8B%E7%BC%A9"><span class="toc-text">shutil和zipfile模块-压缩和解压缩</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%92%E5%BD%92%E7%AE%97%E6%B3%95%E5%8E%9F%E7%90%86-%E8%87%AA%E5%B7%B1%E5%A4%8D%E4%B9%A0%E5%89%8D%E9%9D%A2%E8%AE%B2%E8%BF%87%E7%9A%84%E7%AE%97%E6%B3%95%E5%8E%9F%E7%90%86"><span class="toc-text">递归算法原理-自己复习前面讲过的算法原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%92%E5%BD%92%E7%AE%97%E6%B3%95-%E7%9B%AE%E5%BD%95%E6%A0%91%E7%BB%93%E6%9E%84%E7%9A%84%E5%B1%95%E7%A4%BA"><span class="toc-text">递归算法-目录树结构的展示</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97"><span class="toc-text">模块</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%BC%96%E7%A8%8B%E7%90%86%E5%BF%B5-%E4%BB%80%E4%B9%88%E6%98%AF%E6%A8%A1%E5%9D%97-%E5%93%B2%E5%AD%A6%E6%80%9D%E6%83%B3"><span class="toc-text">模块化编程理念-什么是模块-哲学思想</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%BC%96%E7%A8%8B%E7%9A%84%E6%B5%81%E7%A8%8B-%E8%AE%BE%E8%AE%A1%E5%92%8C%E5%AE%9E%E7%8E%B0%E5%88%86%E7%A6%BB%E7%9A%84%E6%80%9D%E6%83%B3"><span class="toc-text">模块化编程的流程-设计和实现分离的思想</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%AF%BC%E5%85%A5-import%E5%92%8Cfrom-import%E8%AF%A6%E8%A7%A3%E5%92%8C%E5%8C%BA%E5%88%AB"><span class="toc-text">模块导入-import和from_import详解和区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#import%E5%8A%A0%E8%BD%BD%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86-importlib%E5%AE%9E%E7%8E%B0%E5%8A%A8%E6%80%81%E5%AF%BC%E5%85%A5"><span class="toc-text">import加载底层原理-importlib实现动态导入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8C%85%E7%9A%84%E6%A6%82%E5%BF%B5-%E5%88%9B%E5%BB%BA%E5%8C%85-%E5%AF%BC%E5%85%A5%E5%8C%85"><span class="toc-text">包的概念-创建包-导入包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8C%85%E7%9A%84%E6%A8%A1%E7%B3%8A%E5%AF%BC%E5%85%A5"><span class="toc-text">包的模糊导入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#PIP%E5%AE%89%E8%A3%85%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93"><span class="toc-text">PIP安装第三方库</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#GUI%E7%BC%96%E7%A8%8B"><span class="toc-text">GUI编程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#GUI%E7%BC%96%E7%A8%8B%E5%92%8Ctkinter%E4%BB%8B%E7%BB%8D-%E7%AC%AC%E4%B8%80%E4%B8%AAGUI%E7%A8%8B%E5%BA%8F"><span class="toc-text">GUI编程和tkinter介绍-第一个GUI程序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#PEP8%E7%BC%96%E7%A0%81%E8%A7%84%E8%8C%83-%E7%AA%97%E5%8F%A3%E5%A4%A7%E5%B0%8F%E5%92%8C%E4%BD%8D%E7%BD%AE"><span class="toc-text">PEP8编码规范-窗口大小和位置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#GUI%E7%BC%96%E7%A8%8B%E6%95%B4%E4%BD%93%E6%8F%8F%E8%BF%B0-%E5%B8%B8%E7%94%A8%E7%BB%84%E4%BB%B6%E6%B1%87%E6%80%BB"><span class="toc-text">GUI编程整体描述-常用组件汇总</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#GUI%E7%A8%8B%E5%BA%8F%E7%9A%84%E7%BB%8F%E5%85%B8%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E5%86%99%E6%B3%95"><span class="toc-text">GUI程序的经典面向对象写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E7%BB%84%E4%BB%B6"><span class="toc-text">简单组件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Label%E6%A0%87%E7%AD%BE-tkinter%E4%B8%AD%E5%9B%BE%E5%83%8F%E6%AD%A3%E7%A1%AE%E6%98%BE%E7%A4%BA%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%E5%86%99%E6%B3%95"><span class="toc-text">Label标签-tkinter中图像正确显示全局变量写法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Options%E9%80%89%E9%A1%B9%E8%AF%A6%E8%A7%A3-%E5%BA%95%E5%B1%82%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%E5%92%8C%E9%98%85%E8%AF%BB-%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E5%92%8C%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD%E5%A4%8D%E4%B9%A0"><span class="toc-text">Options选项详解-底层源码分析和阅读-可变参数和运算符重载复习</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Button-anchor%E4%BD%8D%E7%BD%AE%E6%8E%A7%E5%88%B6"><span class="toc-text">Button-anchor位置控制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Entry%E5%8D%95%E8%A1%8C%E6%96%87%E6%9C%AC%E6%A1%86-StringVar-%E7%99%BB%E5%BD%95%E7%95%8C%E9%9D%A2%E8%AE%BE%E8%AE%A1%E5%92%8C%E5%8A%9F%E5%AE%9E%E7%8E%B0"><span class="toc-text">Entry单行文本框-StringVar-登录界面设计和功实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Text%E5%A4%9A%E8%A1%8C%E6%96%87%E6%9C%AC%E6%A1%86%E8%AF%A6%E8%A7%A3-%E5%A4%8D%E6%9D%82tag%E6%A0%87%E8%AE%B0"><span class="toc-text">Text多行文本框详解-复杂tag标记</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Radiobutton%E5%8D%95%E9%80%89%E6%8C%89%E9%92%AE"><span class="toc-text">Radiobutton单选按钮</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Checkbutton%E5%A4%8D%E9%80%89%E6%8C%89%E9%92%AE"><span class="toc-text">Checkbutton复选按钮</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Canvasl%E7%94%BB%E5%B8%83%E7%BB%84%E4%BB%B6"><span class="toc-text">Canvasl画布组件</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%83%E5%B1%80%E7%AE%A1%E7%90%86%E5%99%A8"><span class="toc-text">布局管理器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Grid%E5%B8%83%E5%B1%80%E7%AE%A1%E7%90%86%E5%99%A8%E8%AF%A6%E8%A7%A3"><span class="toc-text">Grid布局管理器详解</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AE%A1%E7%AE%97%E5%99%A8%E8%BD%AF%E4%BB%B6%E7%95%8C%E9%9D%A2%E7%9A%84%E8%AE%BE%E8%AE%A1"><span class="toc-text">计算器软件界面的设计</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Pack%E5%B8%83%E5%B1%80%E7%AE%A1%E7%90%86%E5%99%A8"><span class="toc-text">Pack布局管理器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%92%A2%E7%90%B4%E8%BD%AF%E4%BB%B6%E7%95%8C%E9%9D%A2%E8%AE%BE%E8%AE%A1"><span class="toc-text">钢琴软件界面设计</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Place%E7%AE%A1%E7%90%86%E5%99%A8"><span class="toc-text">Place管理器</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86"><span class="toc-text">事件处理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%89%91%E5%85%8B%E6%B8%B8%E6%88%8F%E7%95%8C%E9%9D%A2%E8%AE%BE%E8%AE%A1-%E5%A2%9E%E5%8A%A0%E4%BA%8B%E4%BB%B6%E6%93%8D%E4%BD%9C"><span class="toc-text">扑克游戏界面设计-增加事件操作</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F-%E4%BA%8B%E4%BB%B6%E4%BC%A0%E5%8F%82%E5%BA%94%E7%94%A8"><span class="toc-text">lambda表达式-事件传参应用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E7%A7%8D%E4%BA%8B%E4%BB%B6%E7%BB%91%E5%AE%9A%E6%96%B9%E5%BC%8F%E6%80%BB%E7%BB%93"><span class="toc-text">三种事件绑定方式总结</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E7%BB%84%E4%BB%B6"><span class="toc-text">其他组件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#optionmenu%E9%80%89%E9%A1%B9%E8%8F%9C%E5%8D%95"><span class="toc-text">optionmenu选项菜单</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#scale%E6%BB%91%E5%9D%97"><span class="toc-text">scale滑块</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%A2%9C%E8%89%B2%E6%A1%86"><span class="toc-text">颜色框</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E9%80%89%E6%8B%A9%E6%A1%86"><span class="toc-text">文件选择框</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6%E5%86%85%E5%AE%B9"><span class="toc-text">读取文件内容</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E5%AF%B9%E8%AF%9D%E6%A1%86"><span class="toc-text">简单对话框</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%9A%E7%94%A8%E6%B6%88%E6%81%AF%E6%A1%86"><span class="toc-text">通用消息框</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ttk%E5%AD%90%E6%A8%A1%E5%9D%97%E9%97%AE%E9%A2%98"><span class="toc-text">ttk子模块问题</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8F%9C%E5%8D%95"><span class="toc-text">菜单</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%BB%E8%8F%9C%E5%8D%95"><span class="toc-text">主菜单</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%8A%E4%B8%8B%E6%96%87%E8%8F%9C%E5%8D%95"><span class="toc-text">上下文菜单</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%B0%E4%BA%8B%E6%9C%AC%E9%A1%B9%E7%9B%AE"><span class="toc-text">记事本项目</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9001%E3%80%91%E6%89%93%E5%BC%80%E5%92%8C%E4%BF%9D%E5%AD%98%E4%BF%AE%E6%94%B9%E6%96%87%E4%BB%B6%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-text">【01】打开和保存修改文件的实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9002%E3%80%91%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6-%E8%83%8C%E6%99%AF%E8%89%B2%E6%94%B9%E5%8F%98-%E5%BF%AB%E6%8D%B7%E9%94%AE%E5%8A%9F%E8%83%BD"><span class="toc-text">【02】新建文件-背景色改变-快捷键功能</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9003%E3%80%91python%E9%A1%B9%E7%9B%AE%E6%89%93%E5%8C%85%E6%88%90exe%E5%8F%AF%E6%89%A7%E8%A1%8C%E6%96%87%E4%BB%B6"><span class="toc-text">【03】python项目打包成exe可执行文件</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%BB%E5%9B%BE%E9%A1%B9%E7%9B%AE"><span class="toc-text">画图项目</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9001%E3%80%91%E7%95%8C%E9%9D%A2%E5%AE%9E%E7%8E%B0"><span class="toc-text">【01】界面实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9002%E3%80%91%E7%BB%98%E5%88%B6%E7%9B%B4%E7%BA%BF-%E6%8B%96%E5%8A%A8%E5%88%A0%E9%99%A4%E4%B8%8A%E4%B8%80%E4%B8%AA%E5%9B%BE%E5%BD%A2"><span class="toc-text">【02】绘制直线-拖动删除上一个图形</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9003%E3%80%91%E7%AE%AD%E5%A4%B4%E7%9B%B4%E7%BA%BF-%E7%9F%A9%E5%BD%A2%E7%BB%98%E5%88%B6"><span class="toc-text">【03】箭头直线-矩形绘制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9004%E3%80%91%E7%94%BB%E7%AC%94%E5%92%8C%E6%A9%A1%E7%9A%AE%E6%93%A6%E5%AE%9E%E7%8E%B0"><span class="toc-text">【04】画笔和橡皮擦实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%9005%E3%80%91%E6%B8%85%E5%B1%8F-%E9%A2%9C%E8%89%B2%E6%A1%86-%E5%BF%AB%E6%8D%B7%E9%94%AE%E5%A4%84%E7%90%86"><span class="toc-text">【05】清屏-颜色框-快捷键处理</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B8%B8%E6%88%8F%E5%BC%80%E5%8F%91-%E5%9D%A6%E5%85%8B%E5%A4%A7%E6%88%98"><span class="toc-text">游戏开发-坦克大战</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#pygame%E6%A8%A1%E5%9D%97%E7%9A%84%E5%AE%89%E8%A3%85"><span class="toc-text">pygame模块的安装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E5%88%86%E6%9E%90%E9%A1%B9%E7%9B%AE%E9%9C%80%E6%B1%82"><span class="toc-text">面向对象分析项目需求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9D%A6%E5%85%8B%E5%A4%A7%E6%88%98%E9%A1%B9%E7%9B%AE%E6%A1%86%E6%9E%B6%E6%90%AD%E5%BB%BA"><span class="toc-text">坦克大战项目框架搭建</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E8%BD%BD%E4%B8%BB%E7%AA%97%E5%8F%A3"><span class="toc-text">加载主窗口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9D%A6%E5%85%8B%E5%A4%A7%E6%88%98%E4%B9%8B%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86"><span class="toc-text">坦克大战之事件处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B7%A6%E4%B8%8A%E8%A7%92%E6%96%87%E5%AD%97%E7%9A%84%E7%BB%98%E5%88%B6"><span class="toc-text">左上角文字的绘制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E8%BD%BD%E6%88%91%E6%96%B9%E5%9D%A6%E5%85%8B"><span class="toc-text">加载我方坦克</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%91%E6%96%B9%E5%9D%A6%E5%85%8B%E5%88%87%E6%8D%A2%E6%96%B9%E5%90%91%E7%A7%BB%E5%8A%A8"><span class="toc-text">我方坦克切换方向移动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%91%E6%96%B9%E5%9D%A6%E5%85%8B%E7%A7%BB%E5%8A%A8%E4%BC%98%E5%8C%96"><span class="toc-text">我方坦克移动优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%91%E6%96%B9%E5%9D%A6%E5%85%8B%E4%BC%98%E5%8C%962"><span class="toc-text">我方坦克优化2</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E8%BD%BD%E6%95%8C%E6%96%B9%E5%9D%A6%E5%85%8B"><span class="toc-text">加载敌方坦克</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%8C%E6%96%B9%E5%9D%A6%E5%85%8B%E9%9A%8F%E6%9C%BA%E7%A7%BB%E5%8A%A8"><span class="toc-text">敌方坦克随机移动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%8C%E5%96%84%E5%AD%90%E5%BC%B9%E7%B1%BB"><span class="toc-text">完善子弹类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%91%E6%96%B9%E5%9D%A6%E5%85%8B%E5%8F%91%E5%B0%84%E5%AD%90%E5%BC%B9"><span class="toc-text">我方坦克发射子弹</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%90%E5%BC%B9%E7%A7%BB%E5%8A%A8"><span class="toc-text">子弹移动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%90%E5%BC%B9%E6%B6%88%E4%BA%A1%E5%8F%8A%E6%95%B0%E9%87%8F%E6%8E%A7%E5%88%B6"><span class="toc-text">子弹消亡及数量控制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%8C%E6%96%B9%E5%9D%A6%E5%85%8B%E5%8F%91%E5%B0%84%E5%AD%90%E5%BC%B9"><span class="toc-text">敌方坦克发射子弹</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%91%E6%96%B9%E5%AD%90%E5%BC%B9%E4%B8%8E%E6%95%8C%E6%96%B9%E5%9D%A6%E5%85%8B%E7%9A%84%E7%A2%B0%E6%92%9E"><span class="toc-text">我方子弹与敌方坦克的碰撞</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E7%88%86%E7%82%B8%E6%95%88%E6%9E%9C"><span class="toc-text">实现爆炸效果</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%91%E6%96%B9%E5%9D%A6%E5%85%8B%E7%9A%84%E6%B6%88%E4%BA%A1"><span class="toc-text">我方坦克的消亡</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%91%E6%96%B9%E5%9D%A6%E5%85%8B%E6%97%A0%E9%99%90%E9%87%8D%E7%94%9F"><span class="toc-text">我方坦克无限重生</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E8%BD%BD%E5%A2%99%E5%A3%81"><span class="toc-text">加载墙壁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%90%E5%BC%B9%E4%B8%8D%E7%A9%BF%E5%A2%99"><span class="toc-text">子弹不穿墙</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9D%A6%E5%85%8B%E4%B8%8D%E8%83%BD%E7%A9%BF%E5%A2%99"><span class="toc-text">坦克不能穿墙</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%8C%E6%88%91%E5%8F%8C%E6%96%B9%E5%9D%A6%E5%85%8B%E5%8F%91%E7%94%9F%E7%A2%B0%E6%92%9E"><span class="toc-text">敌我双方坦克发生碰撞</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9F%B3%E6%95%88%E5%A4%84%E7%90%86"><span class="toc-text">音效处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9D%A6%E5%85%8B%E5%A4%A7%E6%88%98%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="toc-text">坦克大战完整代码</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/archives/6ca065c5.html" title="SanShui API 使用教程"><img src="http://wallpaper.csun.site/?abc" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="SanShui API 使用教程"/></a><div class="content"><a class="title" href="/archives/6ca065c5.html" title="SanShui API 使用教程">SanShui API 使用教程</a><time datetime="2025-03-13T13:21:12.311Z" title="更新于 2025-03-13 21:21:12">2025-03-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/b5700173.html" title="微信小程序定时订阅消息问题"><img src="http://wallpaper.csun.site/?25" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="微信小程序定时订阅消息问题"/></a><div class="content"><a class="title" href="/archives/b5700173.html" title="微信小程序定时订阅消息问题">微信小程序定时订阅消息问题</a><time datetime="2024-10-17T12:04:53.379Z" title="更新于 2024-10-17 20:04:53">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/638889b7.html" title="深度学习回归任务训练代码模版"><img src="http://wallpaper.csun.site/?24" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="深度学习回归任务训练代码模版"/></a><div class="content"><a class="title" href="/archives/638889b7.html" title="深度学习回归任务训练代码模版">深度学习回归任务训练代码模版</a><time datetime="2024-10-17T12:04:09.066Z" title="更新于 2024-10-17 20:04:09">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/7cb9f0a8.html" title="通过nginx访问tomcat中SpringMVC应用"><img src="http://wallpaper.csun.site/?23" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="通过nginx访问tomcat中SpringMVC应用"/></a><div class="content"><a class="title" href="/archives/7cb9f0a8.html" title="通过nginx访问tomcat中SpringMVC应用">通过nginx访问tomcat中SpringMVC应用</a><time datetime="2024-10-17T12:02:23.321Z" title="更新于 2024-10-17 20:02:23">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/d4b1abad.html" title="下载M3U8格式加密视频"><img src="http://wallpaper.csun.site/?22" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="下载M3U8格式加密视频"/></a><div class="content"><a class="title" href="/archives/d4b1abad.html" title="下载M3U8格式加密视频">下载M3U8格式加密视频</a><time datetime="2024-10-17T12:02:02.720Z" title="更新于 2024-10-17 20:02:02">2024-10-17</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('http://wallpaper.csun.site/?5')"><div id="footer-wrap"><div class="footer_custom_text">更多内容查看<a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/huaiyuechusan/">我的GitHub</a> ！</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.1
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container').forEach(node => {
            if (node.hasAttribute('display')) {
              btf.wrap(node, 'div', { class: 'mathjax-overflow' })
            } else {
              btf.wrap(node, 'span', { class: 'mathjax-overflow' })
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !true) {
  if (true) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><div class="aplayer no-destroy" data-id="875151895" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-volume="0.5"> </div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="Nice,To,Meet,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:32.3%;}.categoryBar-list{max-height: 380px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 320px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(./img/config_img/image-20231112202739060-2023-11-1220-27-56.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/AI大模型/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">AI大模型</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/202310300007012-2023-11-1123-30-55.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/微信小程序/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">微信小程序</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Girl-2023-11-2221_46_26.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/爬虫/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">爬虫</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/202310300007316-2023-11-1123-30-57.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/深度学习/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">深度学习</a><span class="categoryBar-list-count">4</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Cat-2023-11-2221-47-16.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/大数据/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">大数据</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-36-46.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/PyTorch/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">PyTorch</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-36-11.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/多模态推荐系统/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">多模态推荐系统</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Starry-Night-in-Anime-Wallpaper-2023-11-2221-46-39.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/学习总结/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">学习总结</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/page_img/wallhaven-y8lqo7.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/竞赛/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">竞赛</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-34-25.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Python/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">Python</a><span class="categoryBar-list-count">4</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-37-57.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Liunx/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">Liunx</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="博客框架为Hexo_v6.2.0" title=""><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="主题版本Butterfly_v4.3.1" title=""><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用多线部署，主线路托管于Github Pages" title=""><img src="https://img.shields.io/badge/Hosted-Github Pages-brightgreen?style=flat&amp;logo=Github" alt=""/></a><a class="github-badge" target="_blank" href="https://gitee.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用多线部署，备用线路托管于Gitee Pages" title=""><img src="https://img.shields.io/badge/Hosted-Gitee Pages-22DDDD?style=flat&amp;logo=Gitee" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站项目由Github托管" title=""><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&amp;logo=GitHub" alt=""/></a><a class="github-badge" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可" title=""><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&amp;logo=Claris" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="/./js/runtime.js"></script><!-- hexo injector body_end end --></body></html>